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:


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”/>


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

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

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


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=; xmlns:xsi=; version=“2.0” xsi:schemaLocation=;>

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



            <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=”” 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” /–>





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

public class MyJPARepository {

private EntityManager entityManager;

More information from Spring documentation here

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

Comments are closed.