我是 JPA 的新手,我正在尝试一些入门示例项目。我尝试了 GraniteDS 示例项目(“Hello, World”应用程序),并找到了一种hello
更新或插入 java bean 的方法。它看起来对我来说有点糟糕,但另一方面我不确定它应该如何看起来更好。
更新
我不喜欢 Query 必须抛出异常才能知道不Welcome
存在实体的结果。有没有办法以优雅的方式检查是否有任何记录?
package info.alekna.project.services;
import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.NoResultException;
import org.granite.tide.data.DataEnabled;
import org.granite.tide.data.DataEnabled.PublishMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import info.alekna.project.entities.Welcome;
@Service
@DataEnabled(topic="welcomeTopic", publish=PublishMode.ON_SUCCESS)
public class WelcomeServiceImpl implements WelcomeService {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public Welcome hello(String name) {
if (name == null || name.trim().length() == 0)
throw new RuntimeException("Name cannot be null or empty");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Welcome welcome = null;
try {
Query q = entityManager.createQuery("select w from Welcome w where w.name = :name");
q.setParameter("name", name);
welcome = (Welcome)q.getSingleResult();
welcome.setMessage("Welcome " + name + " (" + sdf.format(new Date()) + ")");
}
catch (NoResultException e) {
welcome = new Welcome();
welcome.setName(name);
welcome.setMessage("Welcome " + name + " (" + sdf.format(new Date()) + ")");
entityManager.persist(welcome);
}
return welcome;
}
@Transactional(readOnly=true)
public List<Welcome> findAll() {
return entityManager.createQuery("select w from Welcome w order by w.name", Welcome.class).getResultList();
}
}