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?
DAO stands for "Data Access Object". It abstracts the concept of "getting something from a datastore". Your DAO objects can be implemented with JDBC calls, JPA calls or whatever. Maybe it calls some remote webservice.
Data Access Objects (or DAOs for short) are used as a direct line of connection and communication with our database. DAOs are used when the actual CRUD (CRUD = Create, Read, Update, Delete) operations are needed and invoked in our Java code. These data access objects also represent the “data layer” of our application.
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate, JPA or JDO in a consistent way.
Additionally to replacing JPATemplate , you should enable annotation configuration using <context:annotation-config /> or configure a PersistenceAnnotationBeanPostProcessor to enable the injection of the EntityManager into the DAOs.
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
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
andJpaTemplate
already mention) I'd recommend you to start using theSession
and/orEntityManager
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With