我是JPA的新手,我正在嘗試一些入門示例項目。我嘗試了GraniteDS示例項目(「Hello,World」app),並且發現更新或插入java bean的方法hello
。它對我來說看起來不太好,但另一方面,我不確定它應該看起來更好。Java bean持久化模式
UPDATE 我不喜歡這樣的查詢必須拋出一個異常,要知道,與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();
}
}
到底是什麼你問這個問題? – vainolo
@vainolo我不喜歡那個查詢必須拋出一個異常,以知道歡迎實體沒有結果存在。有什麼方法可以檢查有沒有優雅的記錄? –