JPA 和 DAO - 标准方法是什么?
我正在使用 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
的示例。您更喜欢哪种设计?我的例子有什么问题吗?
I'm developing my first app with JPA/Hibernate and Spring. My first attempt at a DAO class looks like this:
@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();
}
}
I also found some examples using JpaDaoSupport
and JpaTemplate
. Which design do you prefer? Is there anything wrong with my example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想说你的方法看起来完全正确。就我个人而言,我不使用
JpaDaoSupport
或JpaTemplate
,因为您可以使用EntityManager
和Criteria Queries完成您需要的一切。引用自 JavaDoc Jpa模板:
I'd say your approach looks totally sound. Personally I don't use
JpaDaoSupport
orJpaTemplate
because you can do everything you need with theEntityManager
and Criteria Queries.Quote from the JavaDoc of JpaTemplate:
我更喜欢无模板方法(即您当前的方法),因为
,这是 Spring 的建议,如博客文章“所以你还应该使用Spring的HibernateTemplate和/或JpaTemplate吗??”和官方javadoc:
I prefer the template-less approach (i.e. your current approach) because
And this is the Spring recommendation, as summarized in the blog post "So should you still use Spring's HibernateTemplate and/or JpaTemplate??" and the official javadoc:
我个人更喜欢您的方法 - 注入 EntityManager 并直接使用它。但
JpaTemplate
也是一个不错的选择。我不喜欢它,因为增加了另一个不必要的抽象层。I, personally, prefer your approach - inject
EntityManager
and use it directly. ButJpaTemplate
is also a good option. I don't like it, because adds yet another, unnecessary layer of abstraction.我不知道是否有“标准”方法。
如果您使用 JPA,则可以选择以下实现:Hibernate、TopLink 等。
如果您部署到 Google App Engine,则将使用 JPA 与 BigTable 通信。
因此,如果您的目标是最大限度地提高可移植性,坚持 JPA 标准,而不是将自己束缚于 Hibernate 等特定实现,请确保您的 DAO 仅使用 JPA 构造。
I don't know if there's a "standard" approach.
If you're using JPA, you have your choice of implementations: Hibernate, TopLink, etc.
If you deploy to Google App Engine, you'll use JPA talking to BigTable.
So if your objectives are to maximize portability, stick with the JPA standard, and not tie yourself to a particular implementation like Hibernate, make sure that your DAOs only use JPA constructs.