Thursday, July 10, 2008

Spring JPA Example with Hibernate

This took longer than I expected since I was able to reuse the Entity beans from the Hibernate annotation example. I had a lot of trouble getting the right jars to work together. Hopefully the Maven config in the project will help someone else.

The key things besides the classpath to get setup in the example were just the Spring Config and putting the JPA configuration in META-INF/persistence.xml. Also the LocalContainerEntityManagerFactoryBean actually returns a javax.persistence.EntityManagerFactory. I assumed it returned an EntityManger based on the name of the class.

One other point is that JpaDaoSupport has setEntityManger and setEntityManagerFactory as final. So you can't override them, use @Autowired, then super the value to the parent method. I ended up passing in the EntityManagerFactory in the constructor using @Autowired. Which is probably better since it's required, but I'm used to typically using setters in Spring.

Note: This example has the DAO class extend JpaDaoSupport and uses the JpaTemplate, but Spring recommends the native JPA style of coding.

"
JpaTemplate mainly exists as a sibling of JdoTemplate and HibernateTemplate, offering the same style for people used to it. or newly started projects, consider adopting the native JPA style of coding data access objects instead, based on a "shared EntityManager" reference obtained through the JPA @PersistenceContext annotation." (from Spring 2.5.x JPA documentation)

3 comments:

Jim Moore said...

Actually, take a look at the PetClinic sample's EntityManagerClinic. You'll notice that it doesn't use EntityManagerFactory and that it doesn't extend JpaDaoSupport. In general SpringSource recommends that you use @PersistenceContext when working with JPA, and that you do not extend from any of the *DaoSupport classes. (Part of the point of Spring is being minimally invasive, and extending from those classes makes you immediately non-POJO. It also limits what you can do, as you noticed.)

David Winterfeldt said...

Thanks. I had actually seen this, but it was getting late one night and this was as far as I had gotten. I still thought it was worthwhile posting since it was functional and planned on doing another example with @PersistenceContext. I'll add a note to the blog and example mentioning that this isn't the way Spring recommends to do things with JPA so no one gets confused.

Amaresh said...

It definitely was worthwhile posting. I was dying to find this JPA approach with hibernate. Thanks a ton both Jim and Dave..