Thursday, October 13, 2011

Spring 3.1.0.RC1 - JPA EntityManagerFactory bootstrapping without persistence.xml

This will be a quick post. Today Spring 3.1.0.RC1 has been released. See here. This article will take a quick look on one of the enhancements in Spring 3.1:

3.1.12 JPA EntityManagerFactory bootstrapping without persistence.xml
In standard JPA, persistence units get defined through META-INF/persistence.xml files in specific jar files which will in turn get searched for @Entity classes. In many cases, persistence.xml does not contain more than a unit name and relies on defaults and/or external setup for all other concerns (such as the DataSource to use, etc). For that reason, Spring 3.1 provides an alternative: LocalContainerEntityManagerFactoryBean accepts a 'packagesToScan' property, specifying base packages to scan for @Entity classes. This is analogous to AnnotationSessionFactoryBean's property of the same name for native Hibernate setup, and also to Spring's component-scan feature for regular Spring beans. Effectively, this allows for XML-free JPA setup at the mere expense of specifying a base package for entity scanning: a particularly fine match for Spring applications which rely on component scanning for Spring beans as well, possibly even bootstrapped using a code-based Servlet 3.0 initializer.

Source: New Features and Enhancements in Spring 3.1

Here's my existing configuration:


This requires an extra META-INF/persistence.xml to make it work:


How do we improve this?

Based on the docs, we can remove the persistence.xml altogether. But how do we declare the extra configurations related to our ORM? And how does the entityManagerFactory know where our entities are?

Here's how:
1. Delete the META-INF/persistence.xml

2. Declare a packagesToScan property

3. Declare a jpaPropertyMap

Here's the final configuration:


If you want to try this with an actual project, you either create a new one, or you can play with my demo project Spring MVC: Integrating MySQL, MongoDB, RabbitMQ, and AJAX which has a Github repo.

That's all folks!
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring 3.1.0.RC1 - JPA EntityManagerFactory bootstrapping without persistence.xml ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

3 comments:

  1. Thank you for nice idea!

    ReplyDelete
  2. Nice article and i got few questions with this implementation without persistence.xml:
    a) Don't we miss the RESOURCE_LOCAL functionality by the removal of persistence.xml
    b) Assume i have 2 datasources, so i would go with 2 bean definition of LocalContainerEntityManagerFactoryBean class. To obtain those instance of EntityManagerFactory in java class, we have to use @Autowired or @PersistenceContext. If @PersistanceContext how can we differentiate which instance has to be assigned.

    ReplyDelete