Configuring JPA EntityManagerFactory
As mentioned earlier in this chapter, to use JPA in Spring, we need to configure an EntityManagerFactory
in Spring, just like the SessionFactory in Hibernate. Spring supports three types of
EntityManagerFactory configuration.
The first one is using the LocalEntityManagerFactoryBean class. It's the simplest one, which requires
only the persistence unit name. However, since it doesn't support the injection of a datasource and hence
isn't able to participate in global transactions, it's suitable only for simple deployment.
The second option is for use in a JEE 6­compliant container, in which the application server
bootstraps the JPA persistence unit based on the information in the deployment descriptors, so Spring
will be able to look up the entity manager via JNDI lookup. Listing 10-1 shows a code snippet for looking
up an entity manager via JNDI.
Listing 10-1. Looking Up Entity Manager via JNDI
<beans>
<jee:jndi-lookup id="prospring3Emf"
jndi-name="persistence/prospring3PersistenceUnit"/>
</beans>
In the JPA specification, a persistence unit should be defined in the configuration file
META-INF/persistence.xml. However, Spring 3.1 provides a new feature that eliminates this need. We will
show you that feature in this section.
The third option, which is the most common and will be used in this chapter as well as in the
sample application, is the LocalContainerEntityManagerFactoryBean class. It supports the injection of a
datasource and can participate in both local and global transactions. Listing 10-2 shows the
corresponding XML configuration file (app-context.xml).
Listing 10-2. Spring Configuration for LocalContainerEntityManagerFactoryBean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc=http://www.springframework.org/schema/jdbc
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<description>Example configuration to get you started.</description>
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
<bean id="transactionManager"
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home