I usually post about Persistence on Twitter - you can follow me there:

Table of Contents

1. Overview

This is tutorial shows how to set up Spring with JPA, using Hibernate as a persistence provider.

For a step by step introduction about setting up the Spring context using Java based configuration and the basic Maven pom for the project, see this article.

NEW: Here is a video on setting up Hibernate 4 with Spring 4 (I recommend watching in in full 1080p):

2. The JPA Spring Configuration with Java

To use JPA in a Spring project, the EntityManager needs to be set up.

This is the main part of the configuration – and it is done via a Spring factory bean – either the simpler LocalEntityManagerFactoryBean or the more flexible LocalContainerEntityManagerFactoryBean. The latter option is used here, so that additional properties can be configured on it:

public class PersistenceJPAConfig{

   public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
      LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });

      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

      return em;

   public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setUsername( "tutorialuser" );
      dataSource.setPassword( "tutorialmy5ql" );
      return dataSource;

   public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
      JpaTransactionManager transactionManager = new JpaTransactionManager();

      return transactionManager;

   public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
      return new PersistenceExceptionTranslationPostProcessor();

   Properties additionalProperties() {
      Properties properties = new Properties();
      properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
      properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
      return properties;

Also, note that, before Spring 3.2, cglib had to be on the classpath for Java @Configuration classes to work; to better understand the need for cglib as a dependency, see this discussion about the cglib artifact in Spring.

3. The JPA Spring Configuration with XML

The same Spring Configuration with XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 

   <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="org.baeldung.persistence.model" />
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      <property name="jpaProperties">
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/spring_jpa" />
      <property name="username" value="tutorialuser" />
      <property name="password" value="tutorialmy5ql" />

   <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="myEmf" />
   <tx:annotation-driven />

   <bean id="persistenceExceptionTranslationPostProcessor" 
      class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />


There is a relatively small difference between the way Spring is configured in XML and the new Java based configuration – in XML, a reference to another bean can point to either the bean or a bean factory for that bean. In Java however, since the types are different, the compiler doesn’t allow it, and so the EntityManagerFactory is first retrieved from it’s bean factory and then passed to the transaction manager:

txManager.setEntityManagerFactory( this.entityManagerFactoryBean().getObject() );

4. Going full XML-less

Usually JPA defines a persistence unit through the META-INF/persistence.xml file. Starting with Spring 3.1, the persistence.xml is no longer necessary – the LocalContainerEntityManagerFactoryBean now supports a ‘packagesToScan’ property where the packages to scan for @Entity classes can be specified.

This file was the last piece of XML to be removed – now, JPA can be fully set up with no XML.

4.1. The JPA Properties

JPA properties would usually be specified in the persistence.xml file; alternatively, the properties can be specified directly to the entity manager factory bean:

factoryBean.setJpaProperties( this.additionalProperties() );

As a side-note, if Hibernate would be the persistence provider, then this would be the way to specify Hibernate specific properties.

5. The Maven configuration

In addition to Spring Core and persistence dependencies – show in detail in the Spring with Maven tutorial – we also need to define JPA and Hibernate in the project, as well as a MySQL connector:



Note that the MySQL dependency is included as a reference – a driver is needed to configure the datasource, but any Hibernate supported database will do.

6. Conclusion

This tutorial illustrated how to configure JPA with Hibernate in Spring using both XML and Java configuration.

We also discussed how to get rid of the last piece of XML usually associated with JPA – the persistence.xml. The final result is a lightweight, clean DAO implementation, with almost no compile-time reliance on Spring.

As always, the code presented in this article is available over on Github. This is a Maven based project, so it should be easy to import and run as it is.

I usually post about Persistence on Twitter - you can follow me there:

  • Gauthier Peel

    I don’t see any @Transactional on your classes. So how could the works ?

    • The DAO is not @Transactional – the service layer is, and since this article focuses on DAO layer, that’s not included. Note that there is an article dealing specifically with transaction configuration: http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/

      • Gauthier Peel

        thanks, i will check out the whole project.
        I noticed you uused :
        public FooDAO(){ setClazz(Foo.class ); }

        I used the follwing trick (not it is always valid though) in the abstract class :

        private Class clazz;

        public AbstractJpaDAO() {
        this.clazz= ((Class) ((ParameterizedType) getClass().getGenericSuperclass())

        so the subclass does not need to give a value to clazz …

  • mwmahlberg

    Thanks a million for the xml configuration – for me as beeing new to spring I realy had a hard time to figure that one out.

  • Kim

    I tried your tutorial but alas … My entitymanager is always null. Why? Thank you in advance.

    Excuse my English

    • There are many reasons this may happen – did you try to start from the example project the article is pointing to (at the end)?
      Thanks. Eugen.

  • eugene

    Hi.. can’t seem to make it work. I deleted my persistence.xml and have my config in JPA context file.
    When I have persistence.xml, with empty persistence unit. i get an error that class is not mapped. when i deleted persistence.xml i have this error: no persistence.xml.

    Do you know how to solve this?

    • Did you try to clone the example project? That should give a good base to build your JPA configuration upon. If you find any problem starting from this point – please go ahead and create an issue on github and I’ll look into it.
      Thanks. Eugen.

      • eugene

        I tried importing your spring-jpa project. and found no major differences on the setup/configuration. What I noticed is that, the JPA Facets is not clicked in your project. Apparently, this solves my issue when I removed it. Thanks a lot.

        regarding the config above, may i know what’s advisable? using the java config or the xml – jpaConfig? I’m also wondering where are your dispatcher servlet and view resolvers configured. (sorry, just started learning spring/jpa-hibernate) TIA.

        • Glad the sample project helped. As for what to use – java or XML config, these are very much equivalent, so it’s a matter of preference. I a new project, I personally prefer to use java config. The Dispatcher, controllers and generally the web configuration lives in a different config file – this one is simply persistence, with the goal to keep things as separate and decoupled as possible.

      • Abhi

        Hey Eugen

        i wanted to connect two database in the project with this method
        how do you think it is possible using this method

  • Rupanjan Baidya


    Do you have any implementation of mybatis with JPA + Spring Data Solr?

    Thank you in advance.

    • I do not have an already implemented example for this stack yet. I think the MyBatis configuration for JPA should be very similar to the Hibernate implementation, and for Spring Data Solr, I recomend this excelent tutorial.
      Hope it helps.

  • Giuseppe Sergio

    Could you Explain how to make work the project XML-Less in tomcat7?

    how i should declare my web.xml? and the Struts.xml?
    Thank you in advance.

  • Ashish Saraf

    Very nice tutorial to illustrate java class configuration for spring-jpa application. When persistence.xml is used, one can define multiple persistence-unit, for multiple database connections. I would appreciate if you could help with an illustration to define such a scenario using java class configuration.
    Thanks and regards,
    Ashish Saraf

    • Hi Ashis – I will cover this in a subsequent article – since this is more of an introduction than advanced usage. If you need it quickly – I don’t think you’ll have any problem defining multiple datasources and working with them separately. The only thing to keep in mind is that – if you only have one data source and one transaction manager – you’re landing on the “Convention” side of “Conversion over Configuration” – if you have more than one, with different names, you’ll be more on the “Configuration” side.

      • Ashish Saraf

        Hi Eugen,
        Thanks for the reply. Would you suggest some reference documentation to this please.
        I will really appreciate.
        Thanks and regards,
        Ashish Saraf

  • rswrc

    Right now i use JBOSS AS 6.1 and have a persistence.xml nad a myProject-ds.xml where the database url , username, password and driver class name is stored. When i remove persistence.xml should i also remove this *-ds.xml? Anf if yes how do i make it to read on my dev machine my dev database and on the production machince the production db? Right now i can work like this.

    • Not sure about the specifics of working with JBoss 6 (I haven’t worked with it for a while now) – but about the configuration – shouldn’t be hard. Keep in mind that the example above is hardcoded for readability but what you want here is not to hardcode any of these values. Instead you simply load them up from properties – checkout the github project as that uses properties, not hardcoded values. Then – you need a mechanism to load a property based on the environment – you can do that in more than one way – here is a simple one I wrote about. That should sort out both problems. Hope this helps.

      • rswrc

        Thx. Your articles are very well written.

        • No worries, glad you’re finding the articles useful.

  • Thiruppathy.R

    Thank you for the useful details!

  • I don’t think it’s a good idea to create an anonymous inner class that extends Properties. As any inner class, this will keep a reference to its outer class – PersistenceJPAConfig, in this case. This instance (and the outer class reference) are then passed to the LocalContainerEntityManagerFactoryBean (what a class name 😉 ) whose lifecycle might be quite different now or in the future, just to save 1-2 lines of code.

    Creating such anonymous classes is almost always a bad idea, see Rule #3 of our article here.

    • Hey Lukas,
      Thanks for the suggestion – you’re absolutely right – no point in holding on to that reference. I updated the tutorial code and the article to simply initialize a Properties object.

    • Abhi

      Hey Lukas,

      Can you please tell me a way how to configure two databases with this method.

      • Hey Abhi, sorry, I’m not quite sure what you mean…? Perhaps you meant to direct your question to Eugen, instead?

  • raam

    Hey thanks for your great tutorial.
    How can we avoid PersistenceJPAConfig and PersistenceJPAConfigXml and just use applicationContext.xml. In production it does not make sense to have both class file and xml. I am looking for example where we can configure only with the applicationContext.xml. Can you give me some pointers how can I make it.

    Thanks in advance

    • Hey Raam – the article illustrates 2 alternative configurations – one in Java and the other in XML. You only need to use one of them, not both. I personally prefer the Java approach, but feel free to use the XML one if you need to. Hope that clarifies thins. Cheers,

  • Amara Bargougui

    thank you for this tutorial
    where could we define the persistance_unit when we remove persistance.xml file?

    • Amara Bargougui

      I think i found the answer :

      this should be the solution:

      cf : JAVADOC :
      getPersistenceUnitName() :

      Return the name of the persistence unit used to create this EntityManagerFactory, or null if it is an unnamed default.

      • noviceUser


        How to define a persistent unit name if we dont want to use default.

        Thanks in advance

        • Amara Bargougui


          like i said, in this case, you have just to valorize the ‘persistenceUnitName’ property

          cf answer above

  • Tomasz Biniecki

    Right in time. Spent 3 hours yesterday on JPA. The problem is it works all fine on local machine when I do spring rest and everything is configured through Application.java and annotations. As soon I started moving towards configuring servlet through xml and writing persistence.xml it all started falling apart.

  • James Lewis

    Thanks Eugen. This article and the sample project saved me a lot of time figuring out how go ds.xml and persistence.xml less with a WAR in JBoss. Very helpful.

  • Mark Jochum

    Using the code samples in the article, I noticed that the bean method “transactionManager” from section 2 takes an EntityManagerFactory directly. The comment at the end of section 3 indicates that perhaps transactionManager should request the injection of a LocalContainerEntityManagerFactoryBean, is that the case? Great article, thanks for the post!

    • Hey Mark – by injecting the EntityManagerFactory directly, Spring is actually going to use the factory bean to create the dependency under the hood – so you don’t need to. Hope that helps. Cheers,

      • Mark Jochum

        It did, thanks! (sorry for replying so late :P)

  • Very nice tutorial, I just have a question, how to load the class PersistenceJPAConfig?

    • There are several way to bootstrap the Spring context. If you’re dealing with a standard web app, you can check out the web.xml portion in this article for the bootstrapping part. Cheers,

    • Alexandru Matei

      Download the working project for the article to see..Or create a Spring web application with Eclipse or NetBeans.

  • Alexandru Matei

    Please provide an example with two Entity Managers in the Java version (not XML)

    Could you write please an implementation like this but with two data sources ?

    public class PersistenceJPAConfig
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()


    public LocalContainerEntityManagerFactoryBean entityManagerFactoryLegacy()


    Thank you!

  • John

    Hi Eugen, a great tutorial from you, but when i try to test this tutorial then i got several error & failed test. So, how to i repairing this error?
    Failed tests:
    FooServicePersistenceIntegrationTest.whenInvalidEntityIsCreated_thenDataException Expected exception: org.springframework.dao.DataIntegrityViolationException
    FooServicePersistenceIntegrationTest.temp_whenInvalidEntityIsCreated_thenDataException Expected exception: org.springframework.dao.DataAccessException

    Tests in error:
    FooPaginationPersistenceIntegrationTest.givenEntitiesExist_whenRetrievingPage_thenCorrect:91 » IllegalArgument
    FooPaginationPersistenceIntegrationTest.givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions:134 » IllegalState

    • Hey John – I ran both tests and I’m not seeing any errors. Can you please open up an issue on github with the full stack that you’re seeing – and I’ll be happy to get it sorted out. Cheers,

  • Mihai Scripca

    How about when you need to add queries to persistence.xml? Seems that are some problems when calling: namedQueries/trade-booking-log.jpa.xml in persistence.xml…

    • Hey Mihai – the simple solution presented here doesn’t use a persistence.xml – it’s no longer necessary. I would recommend simply defining your queries at the repository/DAO level directly. You can still define named queries via annotations of course, if you need them, and still not worry about the persistence.xml. Hope that helps. Cheers,

  • Hi Eugen, good clear article. I used your PersistenceJPAConfig.java with my Spring4 app and everything works for H2 and embeddedDatabase. When I reconfigured for HSQL and BasicDataSource, read and update (persist) work but insert (save) throws these errors:

    java.sql.SQLException: This function is not supported


    org.hibernate.exception.GenericJDBCException: could not prepare statement

    Thanks, Rob

    • You’re probably using an older version of HSQL – try to upgrade to the latest version and give it a go. Hope it helps. Cheers,

  • noviceUser

    Hi.. very helpful tutorial.. I took help of your tutorial and I have one request regarding using entitymanager. Could you please help me on that? I need to pass entitymanager like below :

    JPAQuery jpaQuery = new JPAQuery(entityManager);

    How can I set entitymanager to JPAQuery

    Thanks in advance.

    • Hey,
      First, I assume you have control over the JPAQuery – you’re instantiating that manually. You simply need to wire in your EntityManager and then pass it to your query object. Hope it helps. Cheers,

  • Carlos Romero


    You can perform the same example but using a datasource in an application server? Weblogic or JBoss EAP? Can you explain me?

    Thank you.

    Best regard

    • Hey Carlos – I do have that on my long term content calendar, but it’s far off – for a few reasons – but mostly that I’m not doing any work in this area right now. Cheers,

  • hugo

    Hello Eugen,

    I’ve followed your tutorial and its working perfectly right now, but i’m facing a problem right now when i’m trying to inject an entityManager with @PersistenceContext annotation. Is it possible to do it with this config or do I need something else ??

    Thanks in advance

    • Hey Hugo – yes, it should be possible and work with no extra configuration (of course if you have it available in your context). Cheers,

  • chanks

    Hi Eugen, I’m pretty much following the same as you have described in the article. I’m running into an issue only when the server is idle for some time and getting this error message “The database manager is not able to accept new requests, has terminated all requests in progress, or has terminated this particular request due to unexpected error conditions detected at the target system.”

    I believe I need to set these datasource parameters spring.datasource.test-on-borrow=true
    spring.datasource.validation-query=SELECT 1 FROM SYSIBM.SYSDUMMY1

    Can you help out where exactly do I set these.


    • Hey Chanks – not really sure what the root cause of that is – I’d need to be able to reproduce it to get the that. My suggestion is – ask the question over on StackOverflow, have a simple way to reproduce it (copy-paste code, or a small project on Github) and then followup with me here with the link – I’d be happy to have a look. Cheers,

  • Abhi

    Every setup is working fine.
    the only issue comes when we try to configure two databases in the project.
    Kindly mention a way we can achive that by using this method.

  • Thank you for the tutorial. I want to know how to use spring 4 with spring boot.

    • That’s cool – so basically an Intro to Spring Boot? Sure, there are plenty of good ones online – including the official reference. The only thing I’m not sure about is if that’s quite relevant in the comments of this particular article.
      Regardless – thanks for letting me know – and keep an eye on the site over the next few months, as there’s indeed new Boot material coming.

      • I have been fascinated by spring boot and Spring Tool Suit as one doesn’t have to care about spring configurations (which is by far the complex thing I faced while learning spring).

        • Yeah, STS is great. I wouldn’t go as far as to say you don’t need to care about the config – tools are fantastic but ultimately you still need to understand what they’re doing and what your application is doing at runtime.
          Now – I fully understand that the learning curve of the Spring config isn’t small. However, it’s well worth investing the time to understand it, if you plan to use Spring consistently.
          Hope that helps. Cheers,

  • Ram S

    How to do using only annotations with persistence.xml? With datasource you have hardcoded the values can we not derive those from persistece.xml (using PU)…?

    • The current solution actually doesn’t have (or need) a persistence.xml.
      However, I did have implementations that were using it – just didn’t document them on the site. I’ll have a quick look and see if it makes sense to add it as a TODO on the Content Calendar.

  • vijay Addhankki

    Hi, I am facing an issue while configuring the multiple entity managers with multiple persistence.xmls via xml, can you pls help me out with the configuration.
    SEVERE [main] org.apache.openejb.config.ReportValidationResults.logResults FAIL … core-web-1.0_A0: @PersistenceContext unitName required, multiple units available: ref “em”, available units [applicationPersistenceUnit, applicationPersistenceUnit, applicationPersistenceUnit, applicationPersistenceUnit]

    Below is configuration:



    Reason being having multiple persistence.xmls is JBPM expects separate set of classes.

  • NicoR

    everything works but I have no idea how to persist an object

    • Hey Nico – well, if everything works, you’ll simply need to inject one of the APIs that’s able to persist.
      For example have a look at this article about building a DAO. Or at this one about doing it with Spring Data JPA.
      Hope these point you in the right direction. Cheers,

      • NicoR

        Thanks for the answer:
        I followed the tutorial step by step, even saw the project in git, but i dont know how to declare the dao’s bean and the entityManager:

        org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘com.ramaproyects.gym.SpringTest’: Unsatisfied dependency expressed through field ‘ejerDao’: No qualifying bean of type [com.ramaproyects.gym.model.db.EjercicioDAO] found for dependency [com.ramaproyects.gym.model.db.EjercicioDAO]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ramaproyects.gym.model.db.EjercicioDAO] found for dependency [com.ramaproyects.gym.model.db.EjercicioDAO]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)}

        • Hey Nico – so, if you worked on the tutorial project in github, that already has the DAO configured and ready to go. So, it may be a good idea to simply use that and see exactly how it’s configured.
          In your case here, you’re trying to wire in that bean without defining it in your context.

  • springusr

    Hi, I am trying to build jpa with postgresql. Problem is how I can specify default schema to use by entity manager. I am thinking probably something like below, but not sure what is property name for so..


    • Yes, you can use a property (if you’re using Hibernate as your JPA implementation): hibernate.default_schema
      If you’re not, you can use the orm.xml to configure it – the persistence-unit-defaults element there takes a schema subelement.
      Hope that helps. Cheers,

  • Dave Nellis

    Great example. The only thing it’s missing is how to put your datasource properties into a file that can be delivered externally. This is such an important best practice it should be part of every “helloword” database example.

    • Hey Dave – I definitely agree that’s important when you go to production.
      The reason I didn’t include it here is – I think it deserves it’s own article and can be out of scope for an intro-level article.
      Keep an eye on the RSS feed of the site over the next couple of months – there are some articles in the works on Spring Cloud – which should definitely address this issue.
      Cheers and thanks for the solid feedback,

  • Jayanta Pramanik

    I need help on multi-tenant support on Spring – JPA configuration with XML. Is there anything ? Here multi-tenant stands for separate database. Three Databases are there MSSQL, MySQL and Postgresql. Name of the databases are same and Table structures are obviously same on all of those three Databases. Any help is welcome.

    • Hey Jayanta – yes, Hibernate supports 3 approaches to multitenancy and different database is one of them. It may be Hibernate specific though, so if you need pure JPA, you’ll have to see exactly what’s supported in the standard.
      Hope that helps. Cheers,