Spring Data JPA Tutorial: Configuration

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.

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.

Additional Reading:

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.
178 comments… add one
  • abhishek Apr 17, 2012 @ 13:31

    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.


  • Dhana kumar Sep 15, 2012 @ 18:52

    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.

    • Petri Sep 16, 2012 @ 13:12

      Hi Dhana,

      The reference documentation of Spring Framework states that by default the transaction is rollbacked when a RuntimeException is thrown. Since NullPointerException extends RuntimeException, this could be the reason why the transaction is rolled back. Do you have any idea why the Role object is not found and null is returned instead?

    • Anonymous Mar 13, 2018 @ 20:11

      how to set users child entity in same page

    • chinmay Feb 24, 2021 @ 11:33

      Thanks for the code. I will try to apply for mine. can you also explain how to set up a simple hibernate4 and spring 3.1 web application without using jpa. especially the part about how to use LocalSessionFactoryBuilder.



  • Dirk Nov 12, 2012 @ 13:32

    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.


    • Petri Nov 12, 2012 @ 14:19

      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.

      • Josh Dec 10, 2012 @ 5:39


        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!

        • Petri Kainulainen Dec 10, 2012 @ 19:38

          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?

  • Josh Dec 16, 2012 @ 21:55

    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.

  • amit Dec 29, 2012 @ 9:08

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

    • Petri Dec 29, 2012 @ 10:12

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

  • SergioK Jan 29, 2013 @ 20:06

    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.

    • Petri Jan 29, 2013 @ 20:30

      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.

  • SergioK Feb 4, 2013 @ 14:51

    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 Feb 4, 2013 @ 21:07

      I am sorry to hear that I lost you in the first step.

      However, I do believe that this information is very relevant to people who want to use Spring Data JPA in web applications.

      On the other hand, I want to help you to find relevant information about Spring Data JPA. Maybe these tutorials are more to your liking:

      • vishal Feb 18, 2016 @ 19:09

        pls provide good examples

        like curdoperations and some useful task to realtime

        • Petri Feb 18, 2016 @ 19:31


          like curdoperations

          Check out this blog post.

          some useful task to realtime

          I am not sure what you mean. Could you clarify this a bit?

  • SergioK Feb 5, 2013 @ 0:08

    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 ??.

    • Petri Feb 5, 2013 @ 8:51

      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.

      • Abdulrhman A. Dec 7, 2013 @ 15:20

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

        • Petri Dec 8, 2013 @ 22:22

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

  • Thiago Henrique Mar 16, 2013 @ 5:23

    Wow only now realized your Tutorials http://www.petrikainulainen.net/tutorials/

    excellent reference, very nice .

    great job , very helpful.

    Thanks again!

    • Petri Mar 16, 2013 @ 10:51

      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.

  • Akram Mar 22, 2013 @ 22:07

    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

    • Petri Mar 22, 2013 @ 22:23

      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.

  • Narciso Parra Jun 27, 2013 @ 19:53

    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

    • Petri Jun 27, 2013 @ 20:27

      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.

      • Narciso Parra Jun 27, 2013 @ 23:48

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

        • Petri Jun 27, 2013 @ 23:53


          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.

  • Boris Jul 23, 2013 @ 14:49

    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 ?

    • Petri Jul 23, 2013 @ 17:46

      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.

  • sawakito Oct 2, 2013 @ 19:15

    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.


  • Martin Dilger Oct 2, 2013 @ 21:44

    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

    • Petri Oct 2, 2013 @ 21:44

      Thanks a lot Martin!

  • Nikolay Oct 9, 2013 @ 22:28

    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 :-)

    • Petri Oct 9, 2013 @ 22:37


      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)!

  • Nikolay Oct 9, 2013 @ 23:35

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

  • Srinivas Oct 22, 2013 @ 5:38

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

    • Petri Oct 22, 2013 @ 10:28

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

  • Ekrem Kamberoglu Oct 26, 2013 @ 22:56

    Great reference! Thank you very much for sharing.

    • Petri Oct 27, 2013 @ 17:42

      You are welcome!

  • Ujj Dec 4, 2013 @ 23:46

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

    • Petri Dec 5, 2013 @ 19:01

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

  • José Luis Herranz Dec 29, 2013 @ 13:45

    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.

    • Petri Dec 29, 2013 @ 14:17

      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.

      • Steve Jan 5, 2016 @ 12:38

        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!


        • Petri Jan 5, 2016 @ 20:46

          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.

  • Edward Beckett Jan 11, 2014 @ 18:43

    Very clean coding... Nice work Petri +1

    • Petri Jan 11, 2014 @ 19:57

      Thanks! I really appreciate your kind words.

  • Francois Jan 15, 2014 @ 11:15

    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)

    • Petri Jan 15, 2014 @ 12:51

      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).

      • D Feb 11, 2014 @ 3:10

        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.


  • Petri Feb 11, 2014 @ 10:10


    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.

    • D Feb 12, 2014 @ 0:42

      Thanks Petri - I'll try the other tutorial and hopefully get my config working.

  • VTS Apr 14, 2014 @ 18:58

    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

    • Petri Apr 14, 2014 @ 20:48

      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.

  • Suresh Kumar Apr 21, 2014 @ 18:46

    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.

  • Diego May 6, 2014 @ 18:43

    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?

    • Petri May 6, 2014 @ 18:49


      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.

      • Diego May 6, 2014 @ 19:26

        Thank you for replying so soon.
        My application context file is in: http://pastebin.com/cXUZ663r

        • Diego May 6, 2014 @ 19:28

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

          Thanks again

          • Petri May 6, 2014 @ 20:55

            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?

          • Diego May 6, 2014 @ 22:00

            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.

          • Petri May 7, 2014 @ 21:06

            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.

  • Leandro Souza May 19, 2014 @ 17:38

    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!

    • Petri May 20, 2014 @ 21:30

      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?

  • Marc May 25, 2014 @ 19:35

    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 !

    • Petri May 26, 2014 @ 20:45

      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.

      • Marc Jun 16, 2014 @ 0:55

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

        • Petri Jun 16, 2014 @ 21:29

          You are welcome!

  • mo Jul 10, 2014 @ 15:16

    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?

    • Petri Jul 10, 2014 @ 16:17

      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.

  • Sanjeev K Jul 29, 2014 @ 14:14

    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

  • Anonymous Oct 4, 2014 @ 21:44

    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.

    • Petri Oct 4, 2014 @ 23:24

      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.
  • Pradip Dec 25, 2014 @ 8:48

    Thanks , very useful and nice explanation

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


    • Petri Dec 26, 2014 @ 11:22

      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.

  • coolscitist Jan 7, 2015 @ 8:17

    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;
    • Petri Jan 7, 2015 @ 19:33

      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.

      • coolscitist Jan 9, 2015 @ 8:59

        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.

        • Petri Jan 9, 2015 @ 19:33

          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.

    • solv9kr Jan 11, 2015 @ 18:00

      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.

      • coolscitist Jan 12, 2015 @ 8:13

        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.

      • coolscitist Jan 14, 2015 @ 5:04

        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.

  • coolscitist Jan 14, 2015 @ 5:07

    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.

  • Mark Feb 11, 2015 @ 8:44

    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?



    • Petri Feb 11, 2015 @ 13:17

      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.

      • Mark Feb 11, 2015 @ 19:20

        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!

        • Petri Feb 12, 2015 @ 18:35

          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?

  • guor Mar 23, 2015 @ 14:06

    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?

  • DungTV Apr 11, 2015 @ 21:09

    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!

    • Petri Apr 11, 2015 @ 21:50


      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.

  • Juan May 13, 2015 @ 21:56

    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.

    • Petri May 13, 2015 @ 22:21

      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!

  • sathish May 20, 2015 @ 11:38

    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

    • Petri May 20, 2015 @ 20:05

      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?

  • ismail May 23, 2015 @ 6:30

    Even I put


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

  • ismail May 23, 2015 @ 6:36

    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.

    • ismail May 23, 2015 @ 6:42

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

      • Petri May 23, 2015 @ 12:32


        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.

  • Ketki Sep 20, 2015 @ 21:15

    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?


    • Ketki Sep 20, 2015 @ 21:17

      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.

      • Petri Sep 20, 2015 @ 22:21

        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.

  • Gaurav Dighe Sep 21, 2015 @ 15:12

    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.

    • Petri Sep 21, 2015 @ 21:41


      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.

  • Manjunath Sep 28, 2015 @ 5:06

    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.

    • Petri Sep 28, 2015 @ 20:33

      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.

  • Souma Jan 15, 2016 @ 8:52

    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


    • Petri Jan 16, 2016 @ 12:23


      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.

  • Guilherme Jan 31, 2016 @ 14:36

    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

    • Petri Jan 31, 2016 @ 16:08

      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?

  • Mayank Feb 9, 2016 @ 12:54

    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.?


    • Petri Feb 9, 2016 @ 17:43

      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).

  • mbeddedsoft Mar 1, 2016 @ 15:40

    Hello Petri,
    I was looking through your tutorial and found it very informative and helpful.
    I have a question, why did you implement TodoMapper class? I typically used Mapper classes when using DAOs and I thought a reason for using Repository, instead of DAO, was so that I would not need to use Mapper classes for my Domain objects anymore.

    Can you please answer?

    thank you,

    • Petri Mar 1, 2016 @ 20:33

      The reason why I need mappers is that I don't want to expose my entities to the web layer. I have also written a blog post that explains why I think that exposing them is a bad idea.

      However, I don't implement these mappers myself when I write real-world applications. I use Dozer, ModelMapper, or jTransfo. However, since this is a tutorial that is meant for beginners, I want to keep things simple and avoid unnecessary dependencies.

      • Rob Apr 5, 2016 @ 11:22

        I'd also like to mention MapStruct http://mapstruct.org as another model mapper, it makes use of code generation but in a way that a human might write it EG: personDto.setName(person.getName())

        I'm not sure how it compares to the others, I've only used Dozer before and that was several years ago. I'm sure that they are all pretty much capable of the same thing but it would be nice to do a feature comparison at some point.

        • Petri Apr 7, 2016 @ 17:48

          Thank you for sharing. I will take a look at it. By the way, it would be interesting to see a some kind of performance comparison as well.

  • Rohit Mar 4, 2016 @ 0:37

    Thank you. Not only your article but also you replies to readers questions are also excellent source of information.

    • Petri Mar 4, 2016 @ 15:01

      You are welcome. Also, thank you for your kind words. I really appreciate them.

  • Jonas Mar 25, 2016 @ 3:21

    Thank you very much for this guide. I am trying to integrate spring data jpa into our application, but I am getting the following error when attempting to start Tomcat:

    Error creating bean with name 'academyRepository': Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.NullPointerException
    Caused by: java.lang.NullPointerException
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:61)
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:26)
    at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)

    Have you ever seen this before, or have any idea what might be causing it? I am using XML configuration and am sure it is correct because this is a established project. The only thing I did was add this entry to our applicationContext.xml:

    And then created a single repository:

    public interface AcademyRepository extends JpaRepository {

    List findByName(String name);

    Thanks for any help you may be able to provide.

    • Petri Mar 29, 2016 @ 17:46

      Hi Jonas,

      I have never seen this exception myself, but I found this StackOverflow question. It seems that this might be caused by "duplicate" configuration. Unfortunately Wordpress removes XML markup from comments => I cannot "guess" what your problem is.

      Could you add your application context configuration files into Pastebin and add the link here?

  • Alex001 Mar 31, 2016 @ 18:54

    Petri, thank you for this nice tutorial. For me it is quite the right level to introduce me to SpringIO. Additional I like your links to corresponding areas like maven and how you describe finding the right way within two or more alternatives!

    • Petri Apr 1, 2016 @ 18:19

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

  • Farooq Ahmed Rahu Jun 3, 2016 @ 10:35

    Hi Petri,

    I have connected my application with oracle, mysql db everything is working fine but when I change the configuration to connect same application with MS Sql Sever tables are not auto created with the entities.
    No exception is returned.

    • Petri Jun 4, 2016 @ 11:42


      I don't have a lot of experience from MS SQL Server. I used it in one project and I was able to create the tables automatically. However, I found one interesting StackOverflow answer that might help you to solve your problem.

      • Farooq Ahmed Rahu Jun 14, 2016 @ 10:52

        Hi Dear Petri,

        Issue has been resolved just by adding both of lines
        and hibernate.dialect=org.hibernate.dialect.SQLServerDialect
        in property file.


        • Petri Jun 20, 2016 @ 22:03


          Great! I am happy to hear that you were able solve your problem.

  • Vishal Jun 15, 2016 @ 19:10

    I have been going through various docs for configuring multiple databases with spring boot 1.3.4 release. I also read spring doc to do this:

    However, the issue is that all the docs talk about configuration of two different data sources but none talks about configuration of two different database platform. I mean, I am looking into how to configure, say, SQLServer and Oracle in my spring boot REST API. I could not find any way where I could define two different hibernate dialect (one for SQLServer and one for Oracle) in my application properties.

    Is it even possible to achieve this. Can you please direct me towards any of your blogs or tutorial that could help.


    • Petri Jun 20, 2016 @ 22:23


      First, I am sorry that it took me so long to answer to your question.

      Second, check out this blog post. Although the example uses two MySQL databases, it is easy to modify the configuration to use different databases (just modify the Spring Boot configuration file).

  • Farooq Ahmed Rahu Jun 22, 2016 @ 9:47

    Hi Dear Petri,

    I don't know where to post this question in your blog or article but writing here..

    I want to create an application in Spring MVC+Spring Security+SpringBoot configured with both JSPs in WEB-INF/views and Thymeleaf in resources/templates.
    or simply the springBoot application with jsps in WEB-INF,
    and should serve the JSP view from running jar file created with maven.

    I have already created web applications in SpringMVC+Spring Security+SpringBoot +Thymeleaf and Spring MVC+Spring Security+JSP.


    • Petri Jun 23, 2016 @ 23:17


      It is a bit tricky to use JSP with Spring Boot. I have to admit that before you asked this question, I had no idea that it is even possible. However, I found a blog post that explains how you can do it (and still use the executable jar file). If you need to use both Thymeleaf and JSP, you should take a look at this StackOverflow question.

      I hope that this helps.

  • Soumadeep Jul 6, 2016 @ 15:36

    I want to develop a simple stand alone Spring Data JPA application with java annotation based configuration.For this I have prepared an entity , a configuration file. Now how to get entityManager in DAO class to execute a simple query.With XML based configuration it is working fine.Please help.

    • Petri Jul 7, 2016 @ 11:56


      If you use Spring Data JPA, you don't need to use the entity manager because you can create repository interfaces and use them instead of the entity manager. If you don't know how you can create or use these repository interfaces, you should take a look at my Spring Data JPA tutorial.

      • Kathie Oct 26, 2017 @ 0:10

        This post is titled Spring Data JPA, and in the first step #3 you talk about configuring the entity manager factory bean. Now you're saying you don't need an entity manager?

        • Petri Oct 26, 2017 @ 12:05

          Well, you need to configure entity manager because Spring Data JPA is just a wrapper that requires a JPA provider. However, you don't need to use the entity manager in your code because you can simply use Spring Data JPA repository interfaces.

          • Kathie Oct 26, 2017 @ 19:03

            Thanks! I'm trying to convert a Springboot POC to Azure. I need to remove the springboot dependency because I have other fights I need to worry about. So I'm trying to figure out what configuration I need to do.

          • Petri Oct 26, 2017 @ 21:41


            You are welcome. Also, it's great that you decided to ask this because it's true that my original comment was misleading. If you have any other questions, don't hesitate to ask them.

  • Manu Dec 23, 2016 @ 9:26

    Can you please show how to view the content of the h2 db while debugging the application. I have seen the stackoverflow comments on how to do it. But not clear on what all configurations are required.

  • chen Jan 30, 2017 @ 16:31

    Your tutorials are very comprehensive. Thank you for your time and effort!

    • Petri Jan 31, 2017 @ 11:17

      You are welcome.

  • mbedded Feb 24, 2017 @ 15:34

    Hello Petri,
    Your Spring JPA tutorials have been an invaluable resource.
    I was wondering do you have any examples or know how I could separate my Spring data entities into a separate Maven project and then configure my primary WebApp to use that data project as a dependency?

    thank you,

    • Petri Mar 4, 2017 @ 11:50


      Are you talking about JPA entities? If so, you can simply include the jar in your classpath and set the value of the packagesToScan property of the LocalContainerEntityManagerFactoryBean bean. Note that I haven't tested this, but AFAIK it should do the trick.

      • Anonymous Aug 9, 2018 @ 8:18

        Which jar??

        • Petri Aug 9, 2018 @ 20:11

          The jar that contains your entities.

  • Pranit Apr 14, 2017 @ 6:35

    Hi Petri,

    Is there a way we can read the JNDI and create Entity Manager Factory without making configuration in XML file

  • werck Apr 21, 2017 @ 22:37

    Spring Data

    Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store.....

    Data access as of April 17, 2012, 13:31. @TabulaRasa

  • LALIT JAMNAL Oct 22, 2017 @ 11:07

    Very useful article. nicely written, so easy to follow. Thanks mate.

    • Petri Oct 23, 2017 @ 17:59

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

  • arun singh Feb 16, 2018 @ 20:11

    really helpful.

    • Petri Feb 21, 2018 @ 13:51

      Thank you.

  • arun singh Feb 24, 2018 @ 16:13

    a big help, thanks

    • Petri Mar 12, 2018 @ 8:43

      You are welcome.

  • Shilpa Jun 5, 2018 @ 11:27

    Thanks this is useful !

  • Tousif Aug 9, 2018 @ 8:16

    Hi petri,
    I am using JPA and I configured all things.
    But still I am getting javax.persistence.TransactionRequiredException.

    • Petri Aug 9, 2018 @ 20:10


      Unfortunately I cannot say what's wrong because you didn't provide enough information, but it seems that for some reason your code isn't run inside a transaction. That's why the entity provider throws the TransactionRequiredException. Can you put your code to Github and share your repository with me?

      • Tousif Aug 10, 2018 @ 10:04

        I am using AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext

        I am getting error at refresh.
        bean of type [org.springframework.orm.jpa.localcontainerentitymanagerfactorybean] is not eligible for getting processed by all beanpostprocessors

  • swapna Oct 15, 2018 @ 20:43

    I want to use spring boot data jpa with jndi which should deploy in websphere. Can you please explain how can i achieve it.

  • Neshi Jul 26, 2019 @ 15:07

    I followed Your tutorial ... unfortunately its seems not complete ... lacks of some supporting information in beetween... what is what and what is puprose of it (but its not so problematic) but when I made copy paste and then I see in my InteliJ in red some variable names and unsuficient declarations / imports etc. For newbie like me it was complete waste of time writing it trying to understand and having now Application like Swiss cheese.
    I understand That You've spent hours on writing this Course I get it and also you helped many ppl ... but for me it was no good. I've learned almost nothing from it! Wasted more than 1 day trying to get it working and for what?
    Good course is like joke ... if you need to explain it its not that good ... and in this case its not good for me at all :/ sorry.
    And I see that specialist will never understand beginners because skipping some knowledge and writing all in shortcuts ... its sucks :/... Im writing this to let you know because after searching a lot of courses without Springboot I''ve found this and ... and its a failure for me :/.

    • Neshi Jul 26, 2019 @ 15:11

      To give you example of many small mistakes :
      You not included applicationContext-persistence.xml and some ppl asked for an example. and in example it was line but you wrote that application.properties should be in config directory so classpath should look like : another thing ...
      - what the heck is that and why its red ... what is it for etc. cmon

      • Petri Jul 26, 2019 @ 22:53


        Thank you for posting these quite interesting comments. It seems you had some (maybe a bit unrealistic) expectations when you started reading my Spring Data JPA tutorial, and you got disappointed because you couldn't just use the code samples without understanding the theory behind them. This is unfortunate.

        However, it's quite common that online tutorials have a very limited scope because Spring is a very complex beast and it's simply not possible to cover everything in one tutorial (especially if the tutorial is free). That's why you have to write your tutorial to a very specific audience. Often this means that these tutorials aren't very useful if you are a beginner.

        That's why I think that if you want to learn how to use Spring Framework, the best way to do it is to get a proper book (like Spring in Action) and read it.

        A few comments about your improvement ideas:

        You not included applicationContext-persistence.xml and some ppl asked for an example.

        The XML configuration doesn't belong to the scope of this tutorial. I left it out simply because I don't use anymore. In words, this was a conscious decision and not a mistake. That being said, I decided to add these files to the example application to this tutorial because I thought that they could be useful to someone who cannot update his/her application to use Java configuration.

        and in example it was line but you wrote that application.properties should be in config directory so classpath should look like : another thing …

        This is a good point. I will add a note that provides additional information about the properties file support of Spring Framework.

  • Nilesh Aug 14, 2020 @ 9:21

    Very easy to understand & too helpful contents , Thanks for such nice contents/Knowledge.

  • SJ Feb 24, 2021 @ 21:32

    I want to store a boolean datatype in an entity to Number(1) type in postgres database.(It works fine if db is oracle).Two approaches already thought of
    1.CustomType annotations
    2.Update entity to handle 0 and 1 with getters setters

    Both the approaches require changing entity class.Is there any better approach maybe in configuaration to notify hibernate/jpa to hamdle boolean type with 0/1

Leave a Reply