If you want to save time by writing less test code, take a look at my upcoming Test With Spring Course.

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 application.properties 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 application.properties file looks as follows:

#Database Configuration

#Hibernate Configuration
The properties found from the application.properties 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.

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 →

119 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 exception..java.lang.NullPointerException.”. 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 application.properties 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="http://www.springframework.org/schema/beans"
        <!-- Read the property values from application.properties -->
        <context:property-placeholder location="classpath:application.properties"/>
        <!-- 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="foo.bar.model"/>
          <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="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</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="foo.bar.repository"/>

      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 http://www.petrikainulainen.net/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 ApplicationContexte.java, 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: https://github.com/dilgerma/spring-data-tutorial.

    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: http://gyazo.com/6e051e955da54de0b2878815d712150f
    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 ApplicationContext.java creating two different DataSource, LocalContainerEntityManagerFactoryBean and JpaTransactionManager. I have also added the corresponding parameters in application.properties 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.

      • Hi Petri,

        Thanks for the link to that blog post from back in 2013. I only just spotted it in my referrer logs!

        Anyway, I thought I’d mention that for anyone trying to do the same in the world of Spring Boot, I have just knocked up an updated post:


        It doesn’t explain things as much as the original post, but is hopefully useful to anyone struggling to persuade Spring Boot to work with multiple data sources. To be honest, the way to do it is almost identical, but there are a couple of gotchas caused by Spring Boot trying to wire everything up based on conventional names.

        Hopefully it might be useful to someone out there. Keep up the good work!


        • Hi Steve,

          Thank you for sharing your new blog post. I am sure that it is useful to my readers. That is why I shared it on Twitter, and I hope that you get some traffic from Twitter.

  • 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 = "org.foo.bar.controller")
    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 = "org.foo.bar.repository")

    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: http://pastebin.com/cXUZ663r

        • My service is in: http://pastebin.com/q8vaV3t3
          and my controller (where the service is injected) is in: http://pastebin.com/McAEAyUF

          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 ApplicationContext.java 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: https://jira.spring.io/browse/SPR-12577

      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?

  • Hi Petri,

    I’m import Part 8 to ecilipse to run.

    I would use JpaRepository annotation, so I have been changed in POM.xml and change version of spring-data-jpa to 1.4.1. And in ApplicationContext.java, I added @EnableJpaRepositories(basePackages={“net.petrikainulainen.spring.datajpa.repository”}) to it.

    When run, I get this error:

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘personRepository’: FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property find found for type net.petrikainulainen.spring.datajpa.model.Person.

    Do you can help me fix it?

    Many Thanks!

    • Hi,

      I would use JpaRepository annotation, so I have been changed in POM.xml and change version of spring-data-jpa to 1.4.1.

      What is the @JpaRepository annotation? I have never heard of it, but I found something from Github. Do you mean that you want to annotate your Spring Data JPA repositories with that annotation?

      By the way, the latest stable release of Spring Data JPA is 1.8.0. I recommend that you use it instead of 1.4.1.

      org.springframework.data.mapping.PropertyReferenceException: No property find found for type net.petrikainulainen.spring.datajpa.model.Person.

      This means that Spring Data JPA expects to find a property called find from the Person class. Because it cannot find it, it throws an exception.

      One possible reason for this is that the name of the custom repository implementation is PaginatingPersonRepositoryImpl. This works with Spring Data 1.1, but if you use Spring Data JPA 1.2.0 (or newer), the name of the custom repository implementation must use this syntax: [The name of the actual repository interface][postfix]. Because the example application uses the default configuration, you must change the name of the custom repository implementation to: PersonRepositoryImpl.

      I assume that the reason why the exception is thrown is that Spring Data JPA tries to create implementations for the methods that are declared in the PaginatingPersonRepository interface (it thinks that they are “standard” query methods). Because it cannot find the find property, it throws an exception.

  • Thanks for the tutorials! are great explained!!

    I just wonder if is possible you know how to call the files of the configurations and where on the project structure put them?


    Note: I removed the empty list and the empty configuration class because they made the comment a bit hard to read – Petri.

    • Hi Juan,

      If you are creating a web application and you use a server that supports the Servlet API 3.0 (or newer), you can create a class that configures the ServletContext programmatically. This configuration class must implement the WebApplicationInitializer interface.

      For example, the example application of this blog post has a package net.petrikainulainen.springdata.jpa.config that contains all @Configuration classes and the custom WebApplicationInitializer class. It doesn’t really matter where you put these classes (as long as they are packaged to the created WAR file), but I like to organize them in this way.

      By the way, the Spring Framework Reference Manual has a pretty comprehensive documentation about the Java-based container configuration.

      I hope that this answers to your question. Also, if you have any further questions, don’t hesitate to ask them!

  • hi Petri,
    Thanks for your useful blog.
    I have a probelm using the spring data,
    i use custom queries to create Query , the entities are mapped by Eclipse link with associaition
    In one particular filter criteria
    i have message table and status table ,where messageid has one to many relation in status table
    there are 4 filter critera three to be filteres with the message table one wiht the status table
    my filter query gets all message entity wiht the status , but i want to get only the elements with latest status which matches with the filter criteria .

    I use pagination , where the page object returns all the message enity that matches the status .but i want the message enetity with only the latest status which matches filter criteria

    • Hi Sathish,

      Unfortunately I am not 100% sure what you are trying to do. Could you leave a new comment to this blog post, and add the relevant entities and your query to that comment?

  • Even I put


    it still ask me version for hibernate and others(only not spring one).

  • sorry for the bad comment above.
    Even I put BOM(dependencyManagment) to pom still asking version. For example I don’t see any version for jpa provider in your pom.xml.
    Am I doing something wrong.

    • I think I realized there is platform-bom and spring-framework-bom. Platform adjusted all versions.

      • Hi,

        Don’t worry about the bad comment. It happens to all of us sometimes.

        I described the dependency management of the example application in the previous part of this tutorial, but you are right. You don’t have to worry about the dependency versions because the Spring IO Platform takes care of them after you have enabled it in your pom.xml file.

        Also, the Spring IO Platform Reference Guide has a section that describes the artifacts which are part of the Spring IO Platform.

  • Hi Petri, thanks for the wonderful blog. It is very easy to read and understand and yes, very up to date. I am hooked here from last two days. I have taken up Spring Data as my topic of study.
    We are already using in it in our project but I just got curious to understand the configurations which have been done already. We are using XML configuration there.

    Question 1: Which configuration method is preferable, Java based or XML?
    Question 2: There is this following bean definition in our applicationContext:

    After a little search through its javadoc n google, I could only understand that it is used for injecting entityManager. But it is optional because a default PersistenceAnnotationBeanPostProcessor is registered by the XML tags.
    Can you please explain a little on this? I am confused as to whether this should be there or not. If it should be, then why?


    • oops.. seems like the code part has been removed once the comment got posted.. I was mentioning about “org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor” bean declaration in application context.

      • Hi Ketki,

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

        Question 1: Which configuration method is preferable, Java based or XML?

        I think that this is a matter of preference. I use Java configuration, but I know some people who like to use XML configuration.

        Question 2: There is this following bean definition in our applicationContext: PersistenceAnnotationBeanPostProcessor?

        It’s probably a remnant from the past, and you don’t need it (unless you want to override something). This StackOverflow question provides more details about the role of the PersistenceAnnotationBeanPostProcessor bean.

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

  • Hello,
    I have previously used SpringMVC and Spring-Data-JPA for project. For this I did XML Configuration.
    In these examples, you have demonstrated Java Configurations, so my question is:
    1. Can we use both kind of configurations – XML and JAVA configurations together or do I need to stay with either of two throughout the application?

    Please reply.

    • Hi,

      1. Can we use both kind of configurations – XML and JAVA configurations together or do I need to stay with either of two throughout the application?

      We can use XML and Java configuration together, but there are some restrictions:

      • If we use Java configuration, we can import XML configuration files by annotating our @Configuration class with the @ImportResource annotation.
      • If we use XML configuration, we can annotate our beans with the relevant annotations (such as @Controller, @Component, @Service, and @Repository) as long as these beans are placed in a package that is scanned by the Spring container. However, if we use XML, we cannot import Java configuration classes (or at least I don’t know a way to do it).

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

  • Hi Petri,

    Thank you for such a nice article and your blogs will help beginners a lot. This is my first spring data project and face some issue with the configuration. Which I posted my query in the following link, http://stackoverflow.com/questions/32811188/no-qualifying-bean-of-type-repository-found-for-dependency-in-spring-data-jpa?noredirect=1#comment53462720_32811188

    Can you please have a look at and help me the needful.

    • Hi Manjunath,

      Typically the NoSuchBeanDefinitionException is thrown when the Spring container cannot find the bean definition. If you want to get more information about this exception, read this blog post: Spring NoSuchBeanDefinitionException.

      Because the missing bean is a Spring Data JPA repository, the most likely reason for this error is that the repository interface is not placed in a package that is scanned by Spring Data JPA. In other words, check that the basePackages attribute of the @EnableJpaRepositories annotation contains the correct package.

      Also, you probably want to change this as well (your entity managers tries to find entities from a wrong package).

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

  • Suppose a join select query returns multiple column from different tables.How can the select query return a specific type of List of bean(not a type of entity) in the @Query of the interface extending JpaRepository interface?

    public interface XYZRepository extends JpaRepository{
    @Query(query=”select ordatt.eNo as eNo, ord.Id as Id from Ord ord,Attr ordatt where ord.Id =ordatt.Id)
    public List selectAllSendOutOrderInfo();

    class XY{
    int eNo;
    int Id;
    //getter and setter


    • Hi,

      Read this comment. It explains how you can create a query method that returns an object, which is not an entity, by using the @Query annotation and JPQL. Also, if you want to return a list of objects, you can use this technique as well.

  • Petri, I was reading this topic : https://github.com/brettwooldridge/HikariCP/wiki/Hibernate4

    Has an official ConnectionProvider class from Hibernate, which should be used instead of the HikariCP implementation.

    Using the class HikariConfig I can set properties like pool size, idle timeout, etc.. but I can’t set the connection provider.

    I tried to set using the application.properties using this line:
    And on PersistenceContext

    But I got an error:
    Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.hikaricp.internal.HikariCPConnectionProvider] as strategy [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]

    Do you know if the HikariCP automaticly sets the hibernate connection provider to com.zaxxer.hikari.hibernate.HikariConnectionProvider, or we need to set this manualy?

    Some relevant doc:

    p.s.: I’m using Hibernate 5 and Hikari 2.4.3

    • Hi Guilherme,

      I have never done this myself, but it seems that if you want to use the new HikariConnectionProvider, you shouldn’t use the HikariConfig class. You should configure HikariCP by using the properties described on the wiki page. In other words, you should pass the configuration to Hibernate that configures the HikariCP connection pool.

      Also, I don’t know if HikariCP supports Hibernate 5 yet. Have you tried downgrading to Hibernate 4.3.6?

  • Hi Petri,

    What are your suggestion on transaction commit in SPring. I mean if we want to commit a single transaction in parts how can it be achieved.?


    • Hi Mayank,

      If you want to commit one transaction in several parts, you need divide it into smaller transactions. The reason for this is that a database transaction must either complete entirely or fail (and have no effect).


Leave a Comment