Do you want to create JPA repositories without writing any boilerplate code? If so, read my Spring Data JPA tutorial!

Spring Data JPA Tutorial: Configuration

The begin of a chess game

After we have declared the required dependencies in our POM file, we have to configure the application context of our Spring application.

This blog post describes how we can configure the persistence layer of a Spring application that uses Spring Data JPA and Hibernate.

Let’s get started.

Additional Reading:

If you are not familiar with Spring Data JPA, you should read the following blog posts before you continue reading this blog post:

Configuring the Persistence Layer of a Spring Application

We can create the configuration class, which configures the persistence layer of a Spring application, by following these steps:

  1. Create the properties file that contains the properties used by our application context configuration class.
  2. Configure the datasource bean.
  3. Configure the entity manager factory bean.
  4. Configure the transaction manager bean.
  5. Enable annotation-driven transaction management.
  6. Configure Spring Data JPA.
If you want to configure the persistence layer of your application by using XML configuration, you should take a look at the example application of this blog post. It has a working XML configuration that should help you to get started.

But before we can get started, we have to create the configuration class that configures the persistence layer of our application. The source code of the PersistenceContext class looks as follows:

class PersistenceContext {

	//Configure the required beans here

Let’s start by creating the properties file.

Creating the Properties File

Often we want to use a slightly different configuration in different environments. A good way to do this is move the configuration to a properties file and use a different properties file in different environments.

The file contains the configuration that is used to configure our example application. We can create this properties file by following these steps:

  1. Configure the database connection of our application. We need to configure the name of the JDBC driver class, the JDBC url, the username of the database user, and the password of the database user.
  2. Configure Hibernate by following these steps:
    1. Configure the used database dialect.
    2. Ensure that Hibernate creates the database when our application is started and drops it when our application is closed.
    3. Configure the naming strategy that is used when Hibernate creates new database objects and schema elements.
    4. Configure the Hibernate to NOT write the invoked SQL statements to the console.
    5. Ensure that if Hibernate writes the SQL statements to the console, it will use prettyprint.

The file looks as follows:

#Database Configuration

#Hibernate Configuration
The properties found from the file are loaded by the ExampleApplicationContext class. If you want to take a closer look at it, you can get it from Github.

Let’s move on and configure the datasource bean.

Configuring the Datasource Bean

We can configure the datasource bean by following these steps:

  1. Ensure that the close() method of the created DataSource object is invoked when the application context is closed.
  2. Configure the database connection. We need to set the name of the JDBC driver class, the JDBC url, the username of database user, and the password of the database user.
  3. Create a new HikariDataSource object and return the created object.

The method that configures the datasource bean looks as follows:

class PersistenceContext {

	@Bean(destroyMethod = "close")
	DataSource dataSource(Environment env) {
		HikariConfig dataSourceConfig = new HikariConfig();

		return new HikariDataSource(dataSourceConfig);
	//Add the other beans here

Let’s move on and configure the entity manager factory bean.

Configuring the Entity Manager Factory Bean

We can configure the entity manager factory bean by following these steps:

  1. Create a new LocalContainerEntityManagerFactoryBean object. We need to create this object because it creates the JPA EntityManagerFactory.
  2. Configure the used datasource.
  3. Configure the Hibernate specific implementation of the JpaVendorAdapter interface. It will initialize our configuration with the default settings that are compatible with Hibernate.
  4. Configure the packages that are scanned for entity classes.
  5. Configure the JPA properties that are used to provide additional configuration to the used JPA provider.

The method that configures the entity manager factory bean looks as follows:

class PersistenceContext {

	LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, 
																Environment env) {
		LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
		entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

		Properties jpaProperties = new Properties();
		//Configures the used database dialect. This allows Hibernate to create SQL
		//that is optimized for the used database.
		jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));

		//Specifies the action that is invoked to the database when the Hibernate
		//SessionFactory is created or closed.

		//Configures the naming strategy that is used when Hibernate creates
		//new database objects and schema elements

		//If the value of this property is true, Hibernate writes all SQL
		//statements to the console.

		//If the value of this property is true, Hibernate will format the SQL
		//that is written to the console.


		return entityManagerFactoryBean;
	//Add the other beans here

Let’s move on and configure the transaction manager bean.

Configuring the Transaction Manager Bean

Because we are using JPA, we have to create a transaction manager bean that integrates the JPA provider with the Spring transaction mechanism. We can do this by using the JpaTransactionManager class as the transaction manager of our application.

We can configure the transaction manager bean by following these steps:

  1. Create a new JpaTransactionManager object.
  2. Configure the entity manager factory whose transactions are managed by the created JpaTransactionManager object.

The method that configures the transaction manager bean looks as follows:

class PersistenceContext {

	JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
		JpaTransactionManager transactionManager = new JpaTransactionManager();
		return transactionManager;
	//Add the other beans here

Let’s move on and enable annotation-driven transaction management.

Enabling Annotation-Driven Transaction Management

We can enable annotation-driven transaction management by annotating the PersistenceContext class with the @EnableTransactionManagement annotation. The relevant part of the PersistenceContext class looks as follows:

class PersistenceContext {
	//The beans are configured here

Let’s move on and configure Spring Data JPA.

Configuring Spring Data JPA

We can configure Spring Data JPA by following these steps:

  1. Enable Spring Data JPA by annotating the PersistenceContext class with the @EnableJpaRepositories annotation.
  2. Configure the base packages that are scanned when Spring Data JPA creates implementations for our repository interfaces.

The relevant part of the PersistenceContext class looks as follows:

@EnableJpaRepositories(basePackages = {
class PersistenceContext {
	//The beans are configured here

That is all folks. We have now successfully configured the persistence layer of our example application. Let’s move on and summarize what we learned from this blog post.


This blog post has taught us two things:

  • If we need to use a different configuration in different environment, we should move this configuration to a properties file.
  • We learned to configure the persistence layer of a Spring application that uses Spring Data JPA and Hibernate.

The next part of this tutorial describes how we can create a Spring Data JPA repository that provides CRUD operations for a simple entity.

P.S. You can get the example application of this blog post from Github.

If you want to learn how to use Spring Data JPA, you should read my Spring Data JPA tutorial.
If you enjoyed reading this blog post, you should follow me on Twitter:

About the Author

Petri Kainulainen is passionate about software development and continuous improvement. He is specialized in software development with the Spring Framework and is the author of Spring Data book.

About Petri Kainulainen →

94 comments… add one

  • excellent article very helpfull!!

    can you also explain how to set up a simple hibernate4 and spring3.1 web application without using jpa. especially the part about how to use LocalSessionFactoryBuilder.


  • Hi Petri,
    I need help in testing declarative transaction handling by spring; Pls dont mind if it is nor related to current thread discussion. I am using Junit to test this, not getting this worked. Here is my simple Junit. Here, the attribute I given, defaultRollback = false means I want to see the row inserted in the table, and if defaultRollback = true,
    it is not inserting the record and finally logs message ”Rolled back transaction after test execution for the context……showing”. Even no exception arised, the transaction is getting rolled back and never inserting the record in the table.

    @ContextConfiguration(locations = "file:WebContent/WEB-INF/applicationContext.xml")
    @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
    public class UserServiceTest {

    private UserService userService;

    private RoleService roleService;

    public void testAddUser() {
    User user = new User();

    user.setJoinedOn(new Date(System.currentTimeMillis()));


    Role role = roleService.findRole(99L);

    // here NPE will be thrown and hence entire transaction must be rolled back.

  • Hi Petri,

    Am trying your Spring Data JPA examples. Standard install and run with Jetty no problem.
    However when trying to import the projects in Eclipse i am getting reference errors on spring-jpa-1.0
    schema referenced from applicationContext. Following a tip on a forum I updated version to 1.2.0.RELEASE instead of 1.0.2.RELEASE.
    But still not able to build from Eclipse.
    Can you give me a tip here.


    • The Spring Data JPA 1.0.2 had a “bug” that caused schema validation errors when STS was used. See this bug report for more details: DATAJPA-160.

      However, as the bug report indicates, this should not cause build failure. When you updated the Spring Data JPA to version1.2.0.RELEASE, did you update both the dependency version (found from pom.xml file) and the application context configuration file?

      Also, since you are using Spring Data JPA version 1.2.0, you do not have to configure Spring Data JPA by using XML. You can start using Java configuration by following these steps:

      1. Update the pom.xml file and set the dependency version of Spring Data JPA to 1.2.0.RELEASE.
      2. Remove the repositories element and the schema declaration from the applicationContext.xml file.
      3. Annotate the ApplicationContext class with the @EnableJpaRepositories annotation and set the base package of your repositories as its value. See the Javadoc of the @EnableJpaRepositories annotation for more details.

      This should solve your problem.

      • Petri,

        I downloaded your source code and loaded the project in STS. When I deployed it to the built-in vFabric tc server it worked fine. I made the changes you listed above and tried deploying it again, but I got a 404 for the home view. Backing out the steps, the 404 seemed related to the modifications to applicationContext.xml. In the end I kept the updated dependency version in the POM and updated the version number in the schema statement to get rid of the error in STS.

        Thanks for this tutorial series!

        • Hi Josh,

          I am glad to hear that you liked my tutorial. About your problem, did you end up using the XML configuration since the Java configuration did not work in the built-in vFabric tc server?

  • I am using a combination of Java configuration and XML configuration, but I had to use the jpa:repositories element in the XML configuration. The 404 in my case seemed to be related to using the @EnableJpaRepositories annotation instead of the xml element.

  • Thanks a lot for all the articles…
    Its people like you that make internet fun and useful!! cheers !!!

    • You are welcome. By the way, your comment just made my day!

  • Why do I need extra information , I like to read example working of Spring Data.
    What is deal with servlet ? Spring config file and main are good enough. Sorry there are too much irrelevant information on the web.

    • The web application initializer is used to configure the web application by using Java configuration. It has the following responsibilities:

      1. Create a new ‘root’ application context.
      2. Register the application application context configuration class to the ‘root’ application context.
      3. Register and map the dispatcher servlet.
      4. Use a context loader listener to manage the lifecycle of the ‘root’ application context.

      In other words, your web application would not do much without the web application initializer (unless you use web.xml for configuring your web application). You can get more information about the WebApplicationInitializer from the API documentation of Spring Framework.

      I hope that this answered to your question.

  • Too complicate . Just explain how to configure DB connection and interface .
    and show simple main class to test it. In you explanation I got lost in the first step.

  • Petri ,
    Could you explain about configuration. We need a file (I don’t like annotation )
    for DB connection. Is’ it ? What is a file name ? location ? and content?
    What is a file contains repository definition is it a standard Spring name and where is a correct location for it ??.

    • Of course. You can create the Spring application context configuration file by following these steps:

      1. Create a properties file that contains the properties used in your application context configuration file. This step is not mandatory but it makes your configuration a bit cleaner.
      2. Read the property values from the properties file. If you don’t want to use properties file, you can skip this step.
      3. Configure the data source bean.
      4. Configure the entity manager factory bean.
      5. Configure the transaction manager bean.
      6. Enable @Transactional annotations.
      7. Configure Spring Spring Data JPA.

      The name of the created properties file is and its content looks as follows:

      #Database Configuration
      #Hibernate Configuration

      The application context configuration (applicationContext-persistence.xml) file looks as follows:

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns=""



        <!-- Read the property values from -->
        <context:property-placeholder location=""/>
        <!-- Configure the data source bean -->
        <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
          <property name="driverClass" value="${db.driver}"/>
          <property name="jdbcUrl" value="${db.url}"/>
          <property name="username" value="${db.username}"/>
          <property name="password" value="${db.password}"/>
        <!-- Create default configuration for Hibernate -->
        <bean id="hibernateJpaVendorAdapter" 
        <!-- Configure the entity manager factory bean -->
        <bean id="entityManagerFactory" 
          <property name="dataSource" ref="dataSource"/>
          <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
          <!-- Set the base package of your model classes -->
          <property name="packagesToScan" value=""/>
          <property name="jpaProperties">
              <prop key="hibernate.dialect">${hibernate.dialect}</prop>
              <prop key="hibernate.ejb.naming_strategy">${hibernate.naming_strategy}</prop>
              <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
              <prop key="">${}</prop>
              <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
        <!-- Configure the transaction manager bean -->
        <bean id="transactionManager" 
          <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <!-- Enable @Transactional annotations -->
          Configure Spring Data JPA and set the base package of the 
          repository interfaces 
        <jpa:repositories base-package=""/>

      Both of these files must be found from the classpath. If you are using Maven, you should put these files to the ‘src/main/resources directory’.

      I hope that this answered to your question.

      • Thank you so much for All you tutorials and with this answer too.

        • You are welcome. I am happy to hear that these tutorials have been useful to you.

  • Wow only now realized your Tutorials

    excellent reference, very nice .

    great job , very helpful.

    Thanks again!

    • Thank you for your kind words.

      I created that page because I wanted to provide a shortcut to the good stuff which I have written. I am happy hear that you like it.

  • Hi Petri, I hope I am not going to waste your time since I am a newbie here, first thank you about all the efforts you are doing so others can learn.

    please what did you mean by this (and how to do it ?) :

    (Note: Remember to create the model and repository packages first. Since it is not possible to add empty directories to the Git staging area, the Github repository does not have them either).
    thanks lot

    • Don’t worry about wasting my time. It is always nice to help other people.

      About your question:

      It is not possible to add empty directory to a Git repository. This means that if you get the example application of this blog post from Github, you have to create the following packages:

      • The net.petrikainulainen.spring.datajpa.model is the base package of model classes.
      • The net.petrikainulainen.spring.datajpa.repository is the base package of Spring Data JPA repositories.

      These packages are not found from Github because they don’t have any classes yet. That is why you have to create them yourself.

      I hope that this answered to your question.

  • Hi petri, I am trying to run de example in eclipse IDE but when deploy in jboss
    I get this ERROR Message:
    ERROR …[org.springframework.web.servlet.tags.MessageTag] (http-localhost- No WebApplicationContext found: no ContextLoaderListener registered?: java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
    No Spring WebApplicationInitializer types detected on classpath

    Can you give me some advice about the problem.

    thanks in advance

    • I started to wonder if it possible to run this application with JBoss because it uses Java configuration for configuring the application context and the web application.

      I did some research and found out that there is an open issue about this in the JBoss issue tracker. I am not a JBoss expert but the issue is not resolved so I assume that Java configuration is not supported at the moment.

      If this is true, you have to

      1. Create an application context configuration file.
      2. Create a web.xml file. Check out this blog post for more details about this (Search for a heading ‘Spring Configuration’).
      3. Delete the Java configuration classes (ApplicationContext and DataJPAExampleInitializer).

      I hope that this answered to your question.

      • Thank… I choose a tomcat 7 server and I already running this tutorial.

        • Great!

          I think that Tomcat is often the best choice for running Spring web applications in the production environment.

          I like to use the Maven Jetty plugin in development environment but Tomcat works just fine like you said.

  • Hi ,
    I create interface
    public interface GreetingRepo extends Repository {

    S save(S entity);
    T findOne(ID primaryKey);
    Iterable findAll();

    and and into applicationContext.xml

    but where I use it define @Autowired
    GreetingRepo repo;

    repo.findAll(); I got java.lang.NullPointerException.
    What is miss here?
    Any idea ?

    • Hi Boris,

      When you create repository interfaces, you must provide two type parameters: type of the entity and type of the entity’s id.

      I assume that the name of your entity class is Greeting and the type of its id is Long.

      Also, I create the repository interface by extending the CrudRepository interface instead of the Repository interface. This way I don’t have declare the repository methods manually.

      In other words, your repository interface should look like this:

      public interface GreetingRepo extends CrudRepository<Greeting, Long> {

      I noticed that your original repository interface extends the Repository interface (instead of JpaRepository or CrudRepository). If you want to specify your repository methods manually, you have to create an intermediate interface and copy the method declarations to that interface. If you want to use the save(), findOne(), and findAll() methods, your repository interfaces should look like this:

      //Intermediate interface
      interface MyBaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
        	T findOne(ID id);
        	Iterable<T> findAll();
      	T save(T entity);
      //Repository interface
      public interface GreetingRepo extends MyBaseRepository<Greeting, Long> {

      More information:

      I hope that this answered to your question.

  • Hi Petri,

    I have created un jar with several JPA repository in it and it works fine when I tested it in the same project. But now I need to use those JPA Repositories (they are interfaces extends JpaRepository) in another project, so I imported the jar into my new project, then I got the err like: “No unique bean of type [**.****.**.ClientRepository] is defined: expected single bean but found 0″. Apparently it failed to load those JPA Repositories beans. I felt quite confused and I’m new for JPA so please help me out.

    Note: I used @EnableJpaRepositories(basePackages=”**.***.***.repository”) in the, and I noticed that annotation seems doesn’t work by giving un package from an external jar. Is that the reason?

    Thank you very much and your articles are really great.


  • Out of curiosity, i just tried it out.
    Indeed, with JavaConfig and @EnableJpaRepositories it does not work. With XML there is no problem.
    A Demo Project could be found here:

    Tested with spring-data 1.3.2

    • Thanks a lot Martin!

  • Hello Petri!

    Thank you for your tutorial!
    I am having one question: how i can run this sample project on Tomcat?
    Need to create web.xml?
    When i run project on Tomcat, i saw something like that:
    But under Jetty it is working very well.
    (It not mere curiosity, I want to use your configuration pattern on production :-)

    • Hi,

      I noticed that you use Tomcat 6. If you want to configure your web application by using Java configuration, you have to use a servlet container which supports the servlet 3.0 specification. In other words, you have to use Tomcat 7 (I just tested this with Tomcat 7.0.40 and it was working).

      If you have to use Tomcat 6, you have to replace the class which implements the WebApplicationInitializer interface with a web.xml file.

      Remember that you can still configure the application context by using Java configuration (no need to replace those classes with XML configuration files)!

  • Thank you Petri!
    I will be using Tomcat 7
    And I best fan of configuring application from Java.

  • Petri – you really rock! Thanks for such a great article.

    • You are welcome. I am happy to hear that this tutorial was useful to you!

  • Great reference! Thank you very much for sharing.

    • You are welcome!

  • Excellent material.
    Not only did you put time and effort in sharing this, but you also patiently answer(all sorts of) questions.

    • Thank you for your kind words! You just made my day.

  • Hi Petri,
    congratulations for your blog, it has helped me a lot in the first steps with Spring JPA.

    Now I’m facing some troubles trying to set up a project with two different databases. What I try to do is manage data from two different MySQL databases. I’ve tried to duplicate the code in creating two different DataSource, LocalContainerEntityManagerFactoryBean and JpaTransactionManager. I have also added the corresponding parameters in file. But when I run the code, at the point in which creates the XXXRepository (the first bean), it generates an exception **No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2**.

    I think that I have to inject the concrete PersistenceContext in some way but I do not know exactly where to do that, in the Repository, in the Service…

    Could you please tell me what I’m doing wrong?

    Thanks a lot for your time and your interest.

    • Hi José,

      I am happy to hear that my blog has been useful to you!

      About your problem:

      When I read your comment, I got the impression that you have the following requirements:

      • You have two groups of entities: A and B. The entities belonging to a group A are “stored” to the database A and the entities belonging to the group B are “stored” to the database B.
      • You want to create different entity managers and transaction managers for databases A and B.

      If this is the case, you should read this blog post which describes how you can use Spring Data JPA with multiple databases.

      I hope that this answer will help you to solve your problem.

  • Very clean coding… Nice work Petri +1

    • Thanks! I really appreciate your kind words.

  • Hi Petri,

    Could you please explain me why you would still keep the applicationContext.xml?

    I created the following class:

    @ComponentScan(basePackages = "")
    public class WebMvcConfig extends WebMvcConfigurerAdapter{
         public void addResourceHandlers(final ResourceHandlerRegistry registry){

    Modified the WebApplicationInitializer to the following:

    webApplicationContext.register(ApplicationConfig.class, WebMvcConfig.class);

    and added the following annotation to the ApplicationConfig class: @EnableJpaRepositories(basePackages = "")

    this seems to do the work and allows me to get rid of the xml files. Am I missing something?

    Otherwise I really appreciate your tutorials. By far the best on the subject. I’d love on advanced predication with querydsl. like linked tables e.g. select * from table_1 where a in (select a from table_2 where whatever). This is one thing that eludes me a bit :) (I’m a complete Business Project Manager)

    • Hi Francois,

      There is no reason to use the XML configuration anymore. This tutorial is based on Spring Data 1.0.X and this version didn’t support Java configuration yet. In other words, your configuration looks good to me (I prefer Java configuration over XML configuration).

      I added your suggestion to my todo list. This is a quite common question so I guess that I should write about it in the near future (I could cover the JPA Criteria API as well).

      • Hi Petri,

        Excellent tutorials. Whilst trying to remove the xml app config however like this post I keep getting the following:
        java.lang.IllegalStateException: LifecycleProcessor not initialized – call ‘refresh’ before invoking lifecycle methods via the context: WebApplicationContext for namespace ‘dispatcher-servlet': startup date [Tue Feb 11 01:02:05 GMT 2014]; root of context hierarchy

        I’ve followed Francois’ steps and tried with spring data jpa versions 1.2 and 1.4.3.

        It would be great to see this one updated with latest versions were appropriate and the java based config.


  • Hi,

    I have never seen that exception before but you could take a look at the example application of my Spring Social tutorial. It configures Spring Data JPA by using Java configuration (no XML). You can get the configuration class from Github.

    I agree that it would be nice if I could update this tutorial to use the latest version of Spring Data JPA. I will try to find the time to do this.

    • Thanks Petri – I’ll try the other tutorial and hopefully get my config working.

  • I am trying to configure Spring Data with spring MVC application and run on Tomcat server. I tried both XML and Java configuration ways. But it doesn’t run when I add dependent jars. Could you please help me with this. I have a created a normal web application and controller and services.
    Thanks in Advance

    • I have a few questions to you:

      • Which Tomcat version do you use?
      • Do you configure your web application by using Java configuration or do you use web.xml?
      • What exactly happens when you try to run the application?

      If you answer to these questions, I might be able to figure out what your problem is.

  • Petri, I have two data sources with different credentials and database and host server names. The datasource_one has regular tables and views where as datasource_two has stored procedures for authentication and authorization. How do I map both datasources and get them CDI’s inside the application. Do you have any simple tutorial or example that we can follow. Appreciate any help.

  • Hi Petri, I tried to apply the basic principles of your post in my web application, but I still can’t make the service I developed work. The service uses two different repositories and I used commons-dbcp to make my application get data. It just seems the @transactional annotation on the service’s method doesn’t work. I don’t know what else I can do. Can I send you a piece of my code so you can tell me what I’m doing wrong?

    • Hi,

      Can you add the source code of your service class and your application context configuration to Pastebin? After you have done this, just add the link here and I will take a look at it.

      • Thank you for replying so soon.
        My application context file is in:

        • My service is in:
          and my controller (where the service is injected) is in:

          Thanks again

          • I forgot to ask one thing:

            is your problem that the clear() method of the TransactionServiceImpl class doesn’t save anything to the database? If that is not the problem, what is it?

          • The problem is that the crear() method isn’t working as a transaction, because when the call for the save method of the second repository throws an exception, there is no rollback of data saved through the call for the save method in the first repository.

          • Where do you you configure the classpath scanning for service classes? Move this <context-scan/> element to the application context configuration file which you added to Pastebin (and remove it from the old file). Also, let me know if this did the trick.

  • Thanks for your great post.
    I am trying to configure Spring JPA.
    I have some questions.
    The DataJPAExampleInitializer isn’t loading.
    Do I need to configure something at web.xml?
    I am using Eclipse, Tomcat 7.
    Thanks very much!

    • You don’t need the web.xml file anymore as long as you deploy the example application to a servlet container which supports the servlet 3.x API (Tomcat 7 supports it).

      Are you trying to deploy the war file to Tomcat 7 or are you trying to start the application in Eclipse by using its Tomcat support?

  • Hi Petri,

    I discoverd your site a few days ago and I love it. It’s amazing.
    After reading your article I decided to convert the xml application configuration files to Java based configuration but I’m encountering a problem with the entityManager.

    My goal is to access to the Derby database of embedded glassfish with Spring Data JPA. It used to work well with the xml files (persistence + web)

    I posted my question on StackOverFlow. Could you have a look please ? I’ve spent hours unsucessfully.

    Could you explain the pros and cons of the entityManager as described in the doc
    Obtaining an EntityManagerFactory from JNDI

    Thank you !

    • Hi Marc,

      Did the answer given to your StackOverflow question solve your problem?

      About your second question: I think the answers of this StackOverflow question answers to your question. Also, pay attention to these tips given in the Spring Framework Reference Manual:

      • Use the LocalEntityManagerFactoryBean in simple deployment environments such as stand-alone applications and integration tests.
      • Obtain the EntityManagerFactory from JNDI when deploying to a Java EE 5 server. Check your server’s documentation on how to deploy a custom JPA provider into your server, allowing for a different provider than the server’s default.
      • Use the LocalContainerEntityManagerFactoryBean for full JPA capabilities in a Spring-based application environment. This includes web containers such as Tomcat as well as stand-alone applications and integration tests with sophisticated persistence requirements.

      If you read this section of the Spring Framework Reference Manual, you will notice that the pros and cons of each approach are described in it.

      I hope that this answered to your question.

      • A little late but… thank you for your help.
        Keep blogging and making tutorials :-)

        • You are welcome!

  • Hi Petri,

    I can’t understand what do with the pom.xml . I do mvn install but generated is not a project structure but only a target directory.

    Where do I place next?

    • Hi Mo,

      if you use the default directory layout of Maven, you have to put your source code to the src/main/java directory (you should of course separate them to packages). Have you checked out the example application of this blog post? If not, I suggest that you take a look at it.

  • Hi Petri,
    Excellent Tutorials.
    I am new to SpringData JPA,I refer your tutorials,I create a tutorial-part-one project using IntelliJ IDE & Maven, Maven is build Successfully,But whenever i run through tomcat server I did not get any out put where i mistake, please help me

    Thank you!,
    Sanjeev K

  • Hi Petri,

    Now I have performance problem when I load application it takes 9-10seconds where server itself
    takes not more than 2, 2.5 seconds. How to load spring jars faster ?
    Thank you.

    • Is the “extra time” spend on loading the Spring application context or does it look like that the server is not doing anything?

      If the log file shows that the extra time is spend when the server loads the Spring application context, you cannot really do anything to it (I will come back to this later).

      On the other hand, if the server appears to be idle, it is probably scanning the jar files of your application. If this is the case, check out this wiki page found from the Jetty wiki: Avoid Slow Deployment.

      If you don’t want to start your server every time when you make a minor change to your application, you can avoid it by using one of these products (there might be others too):

      • JRebel is a commercial product that will help you to be more productive because it can reload Java classes at runtime.
      • Spring Loaded is an open source JVM agent that can reload Java classes at runtime.
  • Thanks , very useful and nice explanation

    Sir which one is better tool develop application in spring Eclipse(Kepler/Luna) or STS


    • Thank you for kind words. I really appreciate them.

      Unfortunately I cannot provide a clear answer to your question because I don’t use Eclipse. However, I assume that the Spring Tool Suite is a better choice because it is customized for developing Spring applications.

  • Hi, I am having problems with multiple transactionManagerRef attribute in @EnableJpaRepositories
    For example, in your PersistenceContext class, I defined two transaction managers transactionManager1 and transactionManager2. Then added transactionManagerRef = “transactionManager1″ inside @EnableJpaRepositories

    But I get error:

    Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2: transactionManager1,transactionManager2

    The error disappears when I remove transactionManager2. Could you help resolving this problem?

    public JpaTransactionManager transactionManager1() {
    	JpaTransactionManager transactionManager = new JpaTransactionManager();
    	return transactionManager;
    public JpaTransactionManager transactionManager2() {
    	JpaTransactionManager transactionManager = new JpaTransactionManager();
    	return transactionManager;
    • Did you remember to configure the used transaction manager when you configured the annotation-driven transaction management? If you did not do this, this will throw the exception you mentioned.

      You might want to check out these links:

      If you have any further questions, don’t hesitate to ask them.

      • Actually, that error came up when I was using JpaRepository’s findAll() method.

        I think it is due to some version incompatibility between spring-data-jpa and spring-orm.

        I actually upgraded all libraries: (spring 4.1.4.RELEASE, hibernate 4.3.7.FINAL and everything else to latest versions). The problem was solved when spring-orm 4.1.4.RELEASE was moved above spring-data-jpa 1.7.1.RELEASE in pom, but problem re-surfaced when spring-data-jpa was placed above spring-orm. Still not exactly sure what was wrong, but I think it is due to mismatch in versions.

        • I agree that this problem is most likely caused by a dependency conflict. You can try to resolve this problem by using the Maven Dependency plugin.

          Anyway, this is a pretty weird problem because I think that Spring Data JPA 1.7.1.RELEASE should be compatible with Spring Framework 4.1.4.RELEASE. I assume that some other dependency is causing this problem, but you will know this for sure after you have analyzed your project by using the Maven dependency plugin.

    • If you’re using Spring 4.1.4, it is a major bug. See:

      This bug is fixed in 4.1.5, 4.2 RC1.

      • So, it is a bug then. I am using Spring 4.1.1 without any problem. Hopefully, upgrading to 4.1.5, after it is released won’t give too much problem. Just wondering why such a bug would even exist in a project as good well developed and maintained as Spring.

      • Thank you for the clarification. I am using Spring 4.1.1 and it works fine! (same code doesn’t work with 4.1.4).

        PS: Looks like my previous comments did not get posted.

  • Also, do you plan on making tutorials about Spring Data Rest? Especially clarifying how to combine our service and controller layers with spring data rest.

  • Hi Petri,

    Great tutorials, very thorough! I’m fairly new to spring, but I was curious if some of this configuration work has been superseded by Spring Boot. I seem to keep reading conflicting information about whether Spring Data JPA is a provider in Spring 4. Do I still need to create a PersistenceContext in the latest Spring?



    • If you use Spring Boot, you don’t have to create the PersistenceContext class (you can use its auto configuration feature). If you want to learn how you can do this, you should read the blog post titled: Accessing Data With JPA.

      • Ah great, I’d gotten that guide working before i found you tutorial and realized this might be the wrong approach for using Boot. Now to figure out why Hibernate can’t find my table resource when I execute my REST methods…

        Thanks for the response!

        • You are welcome!

          By the way, what did you mean when you said that Hibernate cannot find your table resource? Do you mean that it cannot find the database table?

  • Thank you for the reference. But I wonder if spring-data-jpa support multi datasource? Or who can tell me a solution about multi datasource?


Leave a Comment