Setting up Spring JPA support

A basic setup to use JPA with Spring

Step 1 – Enable standard bean post processor for annotations

In spring config xml file, add the following:

<context:annotation-config/>

Step 2 – Setup entity manager factory and JPA transaction manager beans

In spring config xml file, add the followings:

<bean class=“org.springframework.orm.jpa.JpaTransactionManager” id=“transactionManager”>

 <property name=“entityManagerFactory” ref=“entityManagerFactory”/>

 </bean>

 <tx:annotation-driven mode=“aspectj” transaction-manager=“transactionManager”/>

  <bean class=“org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean” id=“entityManagerFactory”>

        <property name=“dataSource” ref=“dataSource”/>

 </bean>

Step 3 – add persistence.xml file to classpath:/META-INF folder

For example, to use Hibernate as provider for MySQL:

<?xml version=“1.0” encoding=“UTF-8” standalone=“no”?>

<persistence xmlns=http://java.sun.com/xml/ns/persistence&#8221; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221; version=“2.0” xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd&#8221;>

<persistence-unit name=“persistenceUnit” transaction-type=“RESOURCE_LOCAL”>

        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>

            <property name=“hibernate.dialect” value=“org.hibernate.dialect.MySQL5InnoDBDialect”/>

            <!– value=”create” to build a new database on each run; value=”update” to modify an existing database; value=”create-drop” means the same as “create” but also drops tables when Hibernate closes; value=”validate” makes no changes to the database –>

            <!–  property name=”hibernate.hbm2ddl.auto” value=”validate”/ –>

            <property name=“hibernate.ejb.naming_strategy” value=“org.hibernate.cfg.ImprovedNamingStrategy”/>

            <property name=“hibernate.connection.charSet” value=“UTF-8”/>

            <property name=“hibernate.show_sql” value=“true”/>

            <!– Uncomment the following two properties for JBoss only –>

            <!– property name=”hibernate.validator.apply_to_ddl” value=”false” /–>

            <!– property name=”hibernate.validator.autoregister_listeners” value=”false” /–>

        </properties>

    </persistence-unit>

</persistence>

Conclusion

That’s it. Now you should be able to have the entity manager injected by using annotation @PersistenceContext. For example:

@Repository
public class MyJPARepository {

@PersistenceContext
private EntityManager entityManager;

More information from Spring documentation here

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

Comments are closed.