我正在使用JPA / Hibernate和
Spring开发我的第一个应用程序.我在DAO课上的第一次尝试看起来像这样:
- @Repository(value = "userDao")
- public class UserDaoJpa implements UserDao {
- @PersistenceContext
- private EntityManager em;
- public User getUser(Long id) {
- return em.find(User.class,id);
- }
- public List getUsers() {
- Query query = em.createQuery("select e from User e");
- return query.getResultList();
- }
- }
我还发现了一些使用JpaDaoSupport和JpaTemplate的例子.你更喜欢哪种设计?我的例子有什么问题吗?
解决方法
我会说你的方法听起来很完美.我个人不使用JpaDaoSupport或JpaTemplate,因为您可以使用EntityManager和Criteria Queries完成所需的一切.
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.