When you are developing Spring Boot applications with database interactions, you typically use Hibernate as the Object Relationship Mapping (ORM) tool.

Instead of directly coupling your code with Hibernate, often you’d rather use Spring Data JPA, a Spring Framework project.

Spring Data JPA makes implementation of the data access layer incredibly easy by abstracting most of the complexities involved in persisting data.

Often when you are working with Hibernate and Spring Data JPA, you will need to see what is happening under the hood. It is very helpful to see the actual SQL statements being generated by Hibernate.

Due to the nature of the abstractions offered by Hibernate and Spring Data JPA, its very easy to inadvertently create n+1 queries; which is VERY detrimental to the performance of your application.

In this post, I’ll share a tip on how to configure Hibernate and Spring Data JPA to log executed SQL statements and used bind parameters.

The Application

For the purpose of this post, I’ve created a simple Spring Boot application. In this application, we can perform CRUD operations on a Product entity.

Here is the  Product entity.


Below is a JUnit test class to save and retrieve products.

If you are new to JUnit, I’d suggest checking out my JUnit series of posts.


Activating Logging in Hibernate

To activate the logging of the executed SQL statements with Spring Boot, set the log level of the org.hibernate.SQL category to DEBUG.

If you wish to see the bind values, you can set the log level of org.hibernate.type.descriptor.sql to TRACE .

If you are new to logging frameworks, refer my series on Log4J2.

Here is the logging configuration in the application.properties.


Here is the log output showing the SQL statements generated by Hibernate.

Activating Logging with Spring Data JPA

If you are using Spring Data JPA with Hibernate as the persistence provider, add the following two lines in application.properties.

Here is the log output.


As you can see, its very easy to enable the logging of SQL statements with Spring Boot and Hibernate.

Being able to see what Hibernate is actually doing with the database is very important.

Often, when I’m working on a Spring Boot project, I will enable the SQL output just as a sanity check. I may believe everything is okay. But I have, in fact, found problems which I was unaware of by examining the SQL output.


Wikipedia defines pagination as “The process of dividing a document into discrete pages, either electronic pages or printed pages”. For a programmer, pagination is the process of dividing a large amount of content to be presented on the UI in chunks. Enterprise Web-based applications, such as search engines, forums, and e-commerce stores use pagination to break up, organize, and present content for increased readability and for a rich user experience. Imagine scrolling down a single page to view 4,84,00,000 results that Google returns when you search for the word “Pagination”. Instead, Google uses pagination to limit the results that are presented to a user per page and provides navigation options to browse the results of the other pages. This is how it looks in Google.

Pagination in Google Search

Pagination is not limited only to Web applications. I have seen Swing-based GUI applications, and also network operations software, CRM, ERP, and inventory control software with pagination enabled. Pagination is a very common use case in software development.

Hibernate, which is one of the most widely adopted ORM framework for Java provides support for pagination. In this post we’ll take a look how we can use features in Hibernate to support pagination.

Pagination Using Query

The Query interface of Hibernate, which is an object-oriented representation of a Hibernate query, provides the setFirstRow() and setMaxResults() methods for pagination. The setFirstRow() method sets the first row to retrieve while the setMaxResults() method sets the maximum number of rows to retrieve from the result set that the Query generates. So if you want to list the first five records from the result set, you will call the methods as query.setFirstResult(0) and query.setMaxResults(5). Note that we passed 0 to setFirstResult() because records in a Query result set starts from the index 0, and we want to start from the first record.

Let’s now set up an application to paginate records stored in a database. For this application, we will use an in memory H2 database. As the first step, we need to add the following dependencies to the Maven POM.

The preceding code adds the H2 database and Hibernate dependencies to the project.

For the application, we will start with a Product entity.


The Product class we wrote above is a simple entity decorated with JPA annotations.

Next, we will write a Hibernate utility class that will provide other components of the application a SessionFactory instance to create Hibernate sessions.


It’s now time to address the main concern of the application – Pagination. Let’s start by writing a ProductDao class.


In the saveProducts() method of the ProductDao class above, we saved 30 Product entities to the database. In the listPaginatedProductsUsingQuery() method, we created a Query instance and called the setFirstResult() and setmaxResults() methods passing the int values that the listPaginatedProductsUsingQuery() method receives as arguments. We executed the query and used an enhanced for loop to log the names of the retrieved products. We also wrote a deleteAllProducts() method to delete all Product records from the database.

We will next write the hibernate.cfg.xml configuration file of Hibernate. Ensure that this file is in your project classpath.


Our application is now ready for test. Let’s write this unit test.

For unit testing, we used JUnit in the test class above. We marked the setUp() and cleanUp() methods with the @Before and @After JUnit annotations. If you are new to JUnit, you can go through my series of posts on JUnit here. In the test method marked with @Test, we called the listPaginatedProductsUsingQuery() method on ProductDao passing 0 to specify the first record and 10 to specify the maximum records to retrieve.

The output on running the test is this.

The output above shows the log messages that list the names of the first ten products stored in the database.

Pagination Using Criteria

Pagination using Criteria is the same as using Query. The Criteria interface, similar to the Query interface, provides the setFirstResult() and setMaxResults() methods to support pagination.

In the ProductDao class, lets add a listPaginatedProductsUsingCriteria() method to perform pagination using Criteria.

In the preceding listPaginatedProductsUsingCriteria() method we wrote above, we called the setFirstRow() and setMaxRows() method on a Criteria instance to perform pagination.

The test code for the listPaginatedProductsUsingCriteria() method is this.

The output of the test is this.

As you can observe in the output above, the names of five products starting from the tenth record are logged.

Calculating the Total Number of Records

A common requirement of pagination is to calculate the total number of records to be displayed in the navigation options of the UI. This figure shows few navigation options that make use of the total number of records.

Navigation Options with Total Records

If you are using Criteria, one simple approach is to make two database calls for every page fetch: One for results and another for the total record count. This approach works fine for simple applications, but is not efficient for enterprise-grade applications receiving millions of requests per day. An efficient approach is to use the same Criteria to retrieve both the results and the result count with a single database call. It can be achieved using ScrollableResults – an interface for objects that allow navigating results by arbitrary increments.

To calculate the total result counts along with the results in a single database call, lets add a static getCriteria() method to ProductDao. This method takes a Hibernate Session, constructs a Criteria from it with a restriction and projections before returning the Criteria to the caller.

The code for the getCriteria() method is this.

In ProductDao, let’s add another method with the name listPaginatedProductsUsingScrollableResults(). This method, in addition to performing pagination, calculates the total record count in the result set.

In Line 6 of the listPaginatedProductsUsingScrollableResults() method above, we called the getCriteria() static method, and then called the scroll() method on the Criteria object. The scroll() method returns a ScrollableResults instance. In Line 7 we moved the ScrollableResults instance to the last record and in Line 8, we calculated the total record count. The rest of the code is all about setting the first result and maximum results for pagination and logging the product names of the paginated records. We finally returned the total record count to the caller in Line 24.

The test code for the listPaginatedProductsUsingScrollableResults() method is this.

The output of the test is this.

As you can observe in the output, the names of the first three products along with the total product count are logged.


Pagination can be handled on the client side, the server side, the database, or a mix of them. Hibernate pagination is done on the server side and, as you have seen, it’s pretty easy to understand and use. Some may argue that handling pagination on the server side results in low UI responsiveness as compared to client side pagination done using JavaScript, jQuery, or some third-party pagination plugins. However, client side pagination can lead to significant lag in the initial page load time for large data sets that are common in enterprise applications.

There is no right or wrong approach for handling pagination. Select the pagination approach that best suits your application requirements. When developing applications that use Hibernate as the ORM framework, it’s logical to make use of the built-in pagination capabilities of Hibernate instead of reinventing the wheel.

You will notice even though this is a website focused on the Spring Framework, Spring was not used in this post. Spring projects such as Spring Data JPA, or other projects like Grails use Hibernate Pagination under the covers. You as the developer do not interact with Hibernate Pagination directly. This is abstracted by the tools you are using. But often, it is important to understand what is going on under the covers.


Out of the box, Spring Boot is very easy to use with the H2 Database. If the H2 database is found on your classpath, Spring Boot will automatically set up an in memory H2 database for your use. But what if you want to use MySQL? Naturally, Spring Boot has support for MySQL and a number of other popular relational databases.

Previously, I wrote about creating a web application using Spring Boot.  Let’s say we want to deploy this application to production and we’ve decided to use MySQL for the database. Changing Spring Boot from H2 to MySQL is easy to do.

MySQL Configuration

For this example, I’m using MySQL installed locally on my MacBook Pro. You’ll need to have a database defined for your use. For this example, I want to create a database for my use. Using the command prompt, you can log into MySQL with this command:

Use the following command to create a database.

You only need to use these commands if you want to use a new database. MySQL is a very robust database. The full capabilities of MySQL are beyond the scope of this tutorial.

MySQL Dependencies

First we need to add the MySQL database drivers to our project. You will need to add the following dependency to your Maven POM file.


Spring Boot Properties

We need to override the H2 database properties being set by default in Spring Boot. The nice part is, Spring Boot sets default database properties only when you don’t. So, when we configure MySQL for use. Spring Boot wont setup the H2 database anymore.

The following properties are need to configure MySQL with Spring Boot. You can see these are pretty standard Java data source properties. Since in my example project, I’m using JPA too, we need to configure Hibernate for MySQL too.

NOTE: If this was actually a production database, you not tell Hibernate to use the create-drop option. This tells Hibernate to recreate the database on startup. Definitely not the behavior we want. You can set this property to the following values: none, validate, update, create-drop. If this was actually a production database, you probably would want to use validate.

Running Spring Boot with MySQL

This is all that needs to be changed to use MySQL with Spring Boot. When you start the project now, MySQL will be used by the Spring Boot application for the database.

Free Introduction to Spring Tutorial

Are you new to the Spring Framework? Checkout my Free Introduction to Spring Online Tutorial.


Get The Source

The source code for this post is available on GitHub here. You can download the source and build the project using Maven.


I was recently asked on my Facebook page, “How do I become a Java Web Developer?” There is  really no simple answer for this question. There are many facets to becoming a Java web developer. I’ve encountered Java developers who were good front end developers, or good backend developers. By ‘front end’, I mean more of the browser side technologies – HTML, CSS, Javascript and then Java templating technologies such as Thymeleaf, Sitemesh, or just good old JSPs. Backend developers are going to have stronger skills with Java, databases (SQL and NoSQL), messaging (JMS/AQMP), and web services (SOAP / REST).

You also have what is known as a “full stack” Java developer. This is my personal skill set. A full stack developer is equally skilled as a front end developer and as a back end developer. This is probably the most difficult track to follow, just because of the diversity of technologies involved. One one day you might be debugging something in JQuery, and the next you’re performance tuning an Oracle database query. It takes time and experience to become a full stack Java developer.

Where to Start?

For aspiring developers, the technology landscape can be overwhelming. The technology landscape is always evolving too. Do you risk learning something that will soon be obsolete?

Client Side Technologies

My advice to new developers is to start with the basics. HTML, CSS, and Javascript. These technologies are core to web development. These technologies are also generic in the sense that it does not matter if you’re a Java web developer, or a Ruby web developer.


HTML – Hypertext Markup Language. This is what makes a web page. You need to have a solid understanding of HTML. Back in the beginning of the World Wide Web HTML was traditionally a file that was served by a web server to the browser. This worked great for static content. Stuff that never changed. But this is becoming rare. People want dynamic content. Thus, the HTML is no longer a static file, the HTML is generated on demand. As a Java Web Developer you’re going to be writing code that generates the HTML document for the web browser. You will need to have a solid understanding of the structure of an HTML document.


CSS – Cascading Style Sheets. This is what styles a page. It controls the fonts, the colors, the layout. While HTML defines the content of a web page, CSS defines how it looks when presented in a browser. For example, you may use one set of CSS rules for a desktop web application, and a different set of CSS rules for a mobile application. Same HTML, but two completely different looks when rendered by the browser.


Javascript – Do stuff on the web page. Do not confuse Javascript with Java. While there are some syntax similarities, these are two completely different programming languages. Javascript is what really drives Web 2.0 applications. Through the use of Javascript, you can dynamically change the HTML/CSS based on user actions, giving the web page a more application like feel for the user.


Hypertext Transfer Protocol – The communication between the client and the web server. I see too many web developers who do not understand HTTP. This is absolutely critical for you to understand. Especially as you get into working with AJAX. You need to know the difference between a POST and a GET. You should have memorized the meanings of HTTP status codes 200, 301, and 404 – and more. As a Java web developer you will work with HTTP everyday.

Server Side Technologies


Java – The question is how to become a Java web developer. So, of course you are going to need to know the Java programming language.In addition to just Java itself, you should be familiar with the Java Servlet API. There’s a number of Java web frameworks, which obscure the usage of the Java Servlet API. When things go wrong, you’re going to need to know what’s happening under the covers.


JPA – Java Persistence API – Using the database. JPA is the standard for working with traditional relational databases in Java. Hibernate is the most popular JPA implementation in use today. As a Java web developer, you’re going to be working with databases. You’ll get getting content from the database to display on a web page, or receiving content from the user to store in the database. Java Web Developers need to know how to use JPA.

Java Application Servers

Java Application Servers – The runtime container for Java web applications. Tomcat is, by far, the most popular Java application server. There is a Java standard for a Web Application Archive file – aka WAR file. These are deployed to Application servers such as Tomcat to provide the runtime environment for your web application. A decade ago, the trend was to use a more complex coupling between your application and the application server. However, the current trend is in favor of a looser coupling between your application and the application server.

Java Frameworks

Notice so far, I have not mentioned anything about the plethora of Java frameworks available for you to use? So far, I’ve described the different technologies you will use as a Java web developer. The client side technologies are completely independent of the server side technologies. Firefox doesn’t care if the server is running Java, Python or .NET. New developers often seem to forget this.

It is possible to do Java web development without using one of the Java frameworks. If you do, you will be writing a lot code to handle things which a framework would take care of for you. Which is why when developing Java web applications, you typically will want to use one of the frameworks.

Spring Framework

The Spring Framework is an outstanding collection of tools for building large scale web applications. Exact metrics are hard to determine, but I’ve seen some estimates which say Spring is used in over 60% of Java based web applications. Which really isn’t too surprising. You have the IoC container and dependency injection from Spring Core. Spring MVC, a mature and flexible MVC based web framework. Spring Security, best in class tool for securing your website. Spring Data to help with persistence. Spring has other projects which will help you in building large scale applications.

There really is no alternative to Spring when it comes to a holistic framework. There are competing technologies against the various Spring Projects. But there is no single solution that has the depth and breadth of the Spring Framework family of projects. In my Introduction to Spring online tutorial, I give you a good overview of the major Spring Framework projects and how they are used to build enterprise class applications.


Grails is a rapid application development framework built on top of Spring. You get everything Spring, and then the productivity benefits of Groovy. I like to describe Grails as Spring with a Groovy wrapper. An oversimplification for sure, but important to remember, Spring is still under the covers.

Grails is seeing more and more use in the enterprise. One of the strengths of Grails is its outstanding community support.

Spring Roo

Spring Roo is a pure Java framework, which seems to try to do what Grails does, without Groovy. I’m not a fan of Spring Roo, and last time I checked neither was the marketplace. Spring Roo has not been widely adopted.


A Scala based Framework. I have not had a chance to try out Play yet. I hear a lot of good things about Play in the marketplace. I feel Play is an interesting alternative. But it’s just not widely used in the enterprise. Not yet at least. Play is getting some encouraging traction.

JBoss Seam

JBoss Seam is probably the closest thing to an alternative to the Spring Framework. JBoss Seam follows the JEE standard. JBoss Seam is a good alternative, with good support, and adoption in the enterprise. JBoss Seam is often criticised as being slower than Spring in terms of development and performance. Some are much more critical of JBoss Seam.


Becoming a Java web developer is not something you can become overnight. There is no book called “Teach yourself Java Web Development in 21 days.” There are no short cuts to becoming a Java web developer. There are a lot of different technologies you need to learn and master. Each of these take time to learn.

Being a Java web developer can be a very rewarding career. You can get started just focusing on the front end, or just the backend technologies. Larger Java development shops will allow you to specialize in one area of the technologies over another.

If I was starting out as a Java web developer today, I probably would focus first on the client side technologies. The client side technologies are agnostic to the server side technologies. Thus, as you’re starting out you will have greater employment options. Compensation on the client side technologies is generally lower than the server side, but it’s a good place to start out. You can quickly gain the skills to be employable, then shift focus and broaden your skill set and later seek better employment opportunities.

, ,

In the first part of this tutorial series on creating a web application using Spring Boot, I showed how to use Spring Initializr to create the Maven project we’re using in this example. In the second part of the tutorial series, I showed you how to configure Spring MVC and ThymeLeaf templates to display a basic web page via Tomcat. In this part of my Spring Boot tutorial series, we’ll setup the H2 database and Spring Data JPA. We will use these tools to persist data to the database in our Spring Boot Web Application.

Database Persistence with Spring Boot

Spring Boot comes with pre-configured options for relational databases. Like other things in Spring Boot, these are enabled by simply having the dependency on your classpath.

While all the interest in the media is around No-SQL databases, relational databases are time proven work horses. They are not going anywhere soon. If you’re doing enterprise application development with the Spring Framework, you’re probably going to be using a relational database.

Hibernate / JPA does a great job of abstracting the persistence layer. If you want to change from Oracle to DB2 or to MySQL, it is just a matter of changing the database drivers. The JPA mapping code you use on your domain POJOs doesn’t change. Your application code does not change.

NOTE – the above statement is 95% true. When changing databases with complex mappings, you’re going to hit minor edge cases here and there.

When developing Spring applications, it is very common to use a in memory database for your development, and then a real database installation for your testing and production environments. Oracle is a great database, but it’s also BIG and resource intensive. I’ve run Oracle on a laptop. It takes a lot of resources. Its a great database, but its not really meant to run from a laptop.

The persistence API in Java follows the Interface Segregation design principle of object oriented design. So, its easy to plug in a different persistence implementation. With Spring managing the dependency injection for us, it makes swapping databases in and out very easy.

What we are going to do in this tutorial is setup an in-memory database, configure a JPA entity, setup Hibernate to automatically create the database tables, and on startup add data to the database for our use and testing.

By doing this, each time we start our application, we have a newly created database, with known data populated into the database tables. It sounds like a lot of work, but it’s really not much. And it does not add very much to your startup time. With the speed of modern computers, even a complex set of tables and data is going to load in just a few seconds.

The advantage of doing this for you as the developer is you’re working against known data while you are doing your development. It also sets you up for being able to automate integration and functional tests with a continuous build server such as Jenkins.

Spring Framework 5
Click here to learn about my Spring Framework 5: Beginner to Guru online course!

H2 Database

The H2 database is a popular database to use when developing Spring applications. H2 is written in Java and is easily runs as an embedded in-memory database. Because it is an embedded in memory database, it makes your build portable. Your build will run anywhere Maven will run.

If you used a database like Oracle or MySQL, now you’ve introduced an external dependency. Your build is no longer portable. If you wanted to do the build under Jekins on a build server, you’d need to install the database on that server or provide a configuration pointing to a database elsewhere.

By using the H2 database as an embedded in memory database, your build remains portable.

H2 Database and Spring Boot

Configuring the H2 database with Spring Boot is very easy. You just need to add the H2 dependency to your Maven Pom. Spring Boot will automatically create the database, setup all the database JDBC objects, and by default configure Hibernate in a create-drop mode. Thus, when Hibernate starts up, it will scan the JPA annotated classes and automatically generate and execute the SQL code needed to create the database tables.


By adding this dependency to your Maven POM, Spring Boot will automatically configure the H2 database.

H2 Database Console

H2 comes with a really cool web based database console you can use to query the database. This is very handy to use when developing with the H2 database and the Spring Framework. When developing the code for this post, I ran into a couple of “gotchas” with setting up the H2 Database Console with Spring Security. It inspired me to write a blog post about it. If you’re following this tutorial step by step, please complete the steps in this post now.

NOTE: When connecting, be sure your JDBC url is set to ‘jdbc:h2:mem:testdb’.

h2 database console

JPA Entities

JPA, which stands for Java Persistence API, is a Java standard. It’s important to remember JPA is just the API (Application Programming Interface) standard. Java itself does not ship with JPA included. For that, you need to include an JPA implementation. There’s number of open source and commercial JPA implementations available.

Spring Framework 5
Become a Spring Framework Guru! Click here to learn about my Spring Framework 5: Beginner to Guru online course!

Hibernate and Spring Boot

Hibernate is by far the most popular. When you include the Spring Data JPA dependency in your Maven POM, Hibernate is included by default. As typical with Spring Boot, Hibernate is setup and configured with sensible default properties.


The Spring Data JPA dependencies includes Hibernate. Spring Boot will automatically configure default Hibernate properties.

Example JPA Entity

In our example application, we’re going to use a product for a ecommerce website. I’ll cover JPA mappings in more detail in future posts. Its a subject that could easily be a tutorial series of its own. For now, we just need a product entity.

By convention, I like to put my entity classes in a package called ‘domain’. This is just my personal habit. Probably something I picked up from working so much with the Grails framework.


Spring Data JPA

Using Spring Data JPA can save you a lot of time when interacting with the database. Spring Data JPA implements the Repository Pattern. This design pattern was originally defined by Eric Evans and Martin Fowler, in their book Domain Driven Design. This is one of those time test computer science books, over a decade old, still remains relevant today.

You don’t need to use Spring Data JPA for this type of project. But using Spring Data JPA will make your life as a developer easier. A common alternative to Spring Data JPA would be to use the widely accepted DAO pattern, The DAO pattern is very similar to the Repository Pattern. The advantage of using Spring Data JPA is that you’ll be writing a lot less code. Spring Data JPA works a lot like Spring Integration Gateways, where you define an interface, and Spring provides the implementation at run time.

Spring Data JPA CRUD Repository

The Spring Data JPA CRUD Repository is my favorite feature of Spring Data JPA. Similar to coding with a Spring Integration Gateway, you can just define an interface. Spring Data JPA uses generics and reflection to generate the concrete implementation of the interface we define.

Defining a repository for our Product domain class is as simple as defining a interface and extending the CrudRepository interface. You need to declare two classes in the generics for this interface. They are used for the domain class the repository is supporting, and the type of the id declared of the domain class.

For our Product domain class we can define a Spring Data JPA repository as follows.


Integration Testing with Spring Data JPA and JUnit

Even though we are building a web application, we can test the persistence layer without creating a WAR file, and without deploying to Tomcat. We want to set up some integration tests to test our JPA mapping and interactions with the Spring Data JPA repository. To do this, we’re going to take advantage of the auto-configuration options available to us in Spring Boot. By doing this, there is a lot of boilerplate code we don’t need to write.

Spring Data JPA Repository Test Configuration

For our integration tests, we’re going to use a Spring Context to wire up beans to support our tests. If we were not using Spring Boot, we’d need to create a number of beans ourselves. Normally we would need to create:

  • The H2 data source
  • The Hibernate Entity Manager
  • A JPA Transaction Manager

But since we’re using Spring Boot, we don’t need to write code to create these beans. For the purposes of our integration tests for our Spring Data JPA repositories, we can complete our Java configuration with just annotations.


While this is an empty Java class file, each of the annotations is very important.

  • @Configuration  tells the Spring Framework this is a Java configuration class.
  • @EnableAutoConfiguration tells Spring Boot to do its auto configuration magic. This is what has Spring Boot automatically create the Spring Beans with sensible defaults for our tests.
  • @EntityScan specifies the packages to look for JPA Entities.
  • @EnableJpaRepositories enables the auto configuration of Spring Data JPA.
  • @EnableTransactionManagement Enables Spring’s annotation driven transaction management

Through this configuration, we have everything we need to use the H2 database with Spring Data JPA in JUnit tests.

Spring Data JPA JUnit Integration Test

With our Spring Java configuration done, our JUnit integration test becomes very simple to write. If you’re new to writing JUnit Integration tests with the Spring Framework, checkout this post where I go into this subject much deeper than I am here. Or if you’re new to JUnit, you may wish to start here.

In this post, I am not going to go in depth with Spring Data JPA. This is fairly large and complex project in the Spring Framework. We’re going to use the CRUD repository from Spring Data JPA. CRUD stands for Create, Read, Update, Delete. Your basic persistence operations. Simply extending the Spring Data JPA’s CRUD Repository interface, as we did above, for the specified Entity we will get methods which will:

  • Save an entity
  • Find an entity based on its ID
  • Check if an entity exists based on its ID
  • Get a list of all entities
  • Get a count of all entities
  • Delete an entity
  • Delete all entities

I’ve written a simple integration test for the Spring Data JPA repository I defined above. In the test, I’m going to do some basic operations, like creating an entity, saving an entity, and fetching an entity from the database. While I’ve written a minimal amount of code in this example, the data is really getting saved into a database. You don’t see any SQL happening, but it is getting generated by Hibernate for us. We’re using an in memory H2 database, which goes away once the test is done. But we could easily change the test to save to a database on disk and prove we’ve persisted the test data. Once you grasp how little code you are writing, and how much is happening under the covers for you, you can appreciate what a powerful tool Spring Data JPA is.


Loading Data Using Spring Data on Startup

Hibernate has a feature to load data on startup. Simply place a file called import.sql on your classpath, and Hibernate will execute the SQL statements in file.

Cool, right?

No, not really. It has us writing SQL statements. What if you’re just doing a prototype? If you change your Entity class, you need to update the SQL. When you’re using Spring Data JPA, this not a very elegant solution. I’m going to shamelessly steal from the Grails community, which has a bootstrap.groovy file which allows us to do things on startup. We have a mature ORM in Hibernate and a really cool tool called Spring Data JPA – why wouldn’t we want to use these tools to load data on startup?

Creating a Product Loader

I previously wrote a post on running code in Spring Boot on Startup. We can use this technique here to utilize the Spring Data JPA repository to populate some data for us to use on startup.


This class implements the ApplicationListner interface, so it gets called upon the ContextRefresedEvent on startup. We’re using Spring to inject the Spring Data JPA repository into the class for our use. In this example, I’m creating two entities and saving them to the database.


Running Product Loader

We still have our Spring Boot application class which was created by the Spring Initializr for us.


When we run this class, it will startup tomcat for us. In the console log, we can see the output of the log statements from our ProductLoader  class.

To run the Spring Boot application from IntelliJ, simply right click on the SpringBootWebApplication class and select “Run ‘SpringBootWebApplica…'”

run spring boot application from intellij

H2 Database Console

While we still have Tomcat up, We can use the H2 Database Console to browse the H2 database console at the URL http://localhost:8080/console.

Note: If you have not, you will need to setup the H2 database console as explained here.

From the H2 database console, you can see the PRODUCT table has been created by Hibernate, and two records have been inserted via the Spring Data JPA repository we created in this tutorial.

h2 database console showing data saved by Spring Data JPA


In this part of my tutorial series on creating a web application using Spring Boot, I’ve shown you how to setup the H2 database and Spring Data JPA for use. You can see how easy it is to persist data to the database using Spring Data JPA repositories.

In the next part of this tutorial series, I’ll show you how to use data retrieved from the Spring Data JPA repository and display it on a web page using Spring MVC, and how to create and update records.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

The source code for this post is available on github. You can download it here.