27 November 2010

Using JPA with Spring

SL-370 module 1 shows an example of using JPA with Java SE.
If you want to use Spring with JPA, the java code is just like in Java EE. Here's how the configuration files for Spring look for an example similar to the Java SE example:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 <persistence-unit name="StockPU" transaction-type="RESOURCE_LOCAL">
 <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
 <properties>
  <property name="javax.persistence.jdbc.user" value="public"/>
  <property name="javax.persistence.jdbc.password" value="public"/>
  <property name="javax.persistence.jdbc.url" 
   value="jdbc:derby:MyDB;create=true"/>
  <property name="javax.persistence.jdbc.driver" 
   value="org.apache.derby.jdbc.EmbeddedDriver"/>
  <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
  <property name="eclipselink.logging.level" value="SEVERE"/>
 </properties>
 </persistence-unit>
</persistence>
Spring XML configuration snippet(e.g. in application-config.xml):
<bean id="entityManagerFactory" 
 class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" 
 lazy-init="true">
 <property name="persistenceUnitName" value="StockPU" />
</bean>
<bean name="transactionManager" 
 class="org.springframework.orm.jpa.JpaTransactionManager">
 <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven />