加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 16:21:14 所属栏目:Java 来源:网络整理
导读:我正在使用JPA / Hibernate和 Spring开发我的第一个应用程序.我在DAO课上的第一次尝试看起来像这样: @Repository(value = "userDao")public class UserDaoJpa implements UserDao { @PersistenceContext private EntityManager em; public User getUser(Lon
我正在使用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完成所需的一切.

引自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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读