开发者

JPA and DAO - what's the standard approach?

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() {
        Quer开发者_Python百科y 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?


I'd say your approach looks totally sound. Personally I don't use JpaDaoSupport or JpaTemplate because you can do everything you need with the EntityManager and Criteria Queries.

Quote from the 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.


I prefer the template-less approach (i.e. your current approach) because

  • it's less invasive, you don't tie DAOs to Spring
  • templates don't offer much value with APIs that use unchecked exceptions

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:

The real question is: which approach to choose??

(...)

So in short (as the JavaDoc for HibernateTemplate and JpaTemplate already mention) I'd recommend you to start using the Session and/or EntityManager API directly if you're starting to use Hibernate or JPA respectively on a new project–remember: Spring tries to be non-invasive, this is another great example!


I, personally, prefer your approach - inject EntityManager and use it directly. But JpaTemplate is also a good option. I don't like it, because adds yet another, unnecessary layer of abstraction.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜