春天 – JPA和DAO – 什么是标准方法?

前端之家收集整理的这篇文章主要介绍了春天 – JPA和DAO – 什么是标准方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用JPA / Hibernate和 Spring开发我的第一个应用程序.我在DAO课上的第一次尝试看起来像这样:
  1. @Repository(value = "userDao")
  2. public class UserDaoJpa implements UserDao {
  3. @PersistenceContext
  4. private EntityManager em;
  5.  
  6. public User getUser(Long id) {
  7. return em.find(User.class,id);
  8. }
  9.  
  10. public List getUsers() {
  11. Query query = em.createQuery("select e from User e");
  12. return query.getResultList();
  13. }
  14. }

我还发现了一些使用JpaDaoSupport和JpaTemplate的例子.你更喜欢哪种设计?我的例子有什么问题吗?

解决方法

我会说你的方法听起来很完美.我个人不使用JpaDaoSupport或JpaTemplate,因为您可以使用EntityManager和Criteria Queries完成所需的一切.

引自JavaDoc of JpaTemplate

JpaTemplate mainly exists as a sibling of JdoTemplate and HibernateTemplate,offering the same style for people used to it. For newly started projects,consider adopting the standard JPA style of coding data access objects instead,based on a “shared EntityManager” reference injected via a Spring bean definition or the JPA PersistenceContext annotation.

猜你在找的Java相关文章