, ,

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.



In the first part of this tutorial series for building a web application using Spring Boot, we looked at creating our Spring project using the Spring Initializr. This handy tool gave us a Spring project to work with, jump starting our development effort by creating the project structure and Maven dependencies for us.

In this post I am going to walk you through enabling rendering a webpage using Thymeleaf and Spring MVC.

Why Thymeleaf?

Traditionally, Spring MVC applications used Java Server Pages, or JSPs to generate html content. JSPs are a mature technology and has been around since the early days of Java. In terms of raw speed, JSPs are hard to beat too. But when you do not need the absolute raw speed of a JSP, you may want to consider alternatives to JSPs which help improve developer productivity.

JSPs offer an HTML ‘like’ syntax. Meaning its close, but not completely compatible with HTML. Thymeleaf on the other hand, aims to be a “Natural Template”. This means the Thymeleaf template file will open and display normally in a browser, while a JSP file does not.

I also have selfish reasons for using Thymeleaf in this tutorial on Spring Boot. I’ve never used it, and I thought it looked like a cool technology to try out.

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

Thymeleaf Configuration and Spring Boot

If you were using just Spring MVC, you would need to configure the Thymeleaf template engine for use. That’s not so when you’re using Spring Boot, because we’ve included the dependency spring-boot-starter-thymeleaf in our Maven POM for the project, so Spring Boot will do some things automatically for us.

By default, Spring Boot configures the Thymeleaf template engine to read template files from /resources/templates .

Effectively, you as the developer just need to start making Thymeleaf templates and dropping them into  /resources/templates.

Thymeleaf Template

Let’s start with a very basic HTML file to show.

Thymeleaf Template – index.html

A few things I’d like to point out in the HTML:

  • Line 1 – Is the standard declaration for HTML 5
  • Line 2 – sets a XML Namespace for Thymeleaf. This is important as you start to use the Thymeleaf extensions.
  • Line 6 – Defines the character set for the HTML file.

Spring MVC Controller

The next step we need to take care of is creating a Spring MVC controller. Because we’ve included the dependency spring-boot-starter-web, Spring Boot automatically configured Spring MVC for us. We also get an embedded instance of Tomcat to run our application in too. This may sound simple, but it does take care of a lot of setup tasks that we would normally need to do if we were using Spring MVC without Spring Boot.

With using Spring Boot, we only need to define our controller class, nothing else. Like other things Spring Boot sets up sensible defaults for us.


At this point, we just need a very simple controller. We want to map the web root path (“/”) to the index template. A common convention used in Spring MVC is to return the string name of the template file, less the file extension. Thus to show the index.html file we defined above, our controller method needs to return the string ‘index’,

On Line 6, I’ve used the @Controller  annotation to make this class a Spring component and a Spring MVC controller. On line 9, you can see that I annotated the index()  method with a @RequestMapping  annotation. By doing this, I’ve configured the root path to this controller method.

Running the Example

If you’re using IntelliJ, you can go into the class SpringBootWebApplication  and right click on the main()  method, then click on run. This will run the Spring Boot application. Spring Boot will startup an embedded instance of Tomcat and deploy our application to it.

BUT – if you navigate to http://localhost:8080 via your browser, the port Tomcat is listening on, you will see this:

Basic Auth via Spring Security

So, what’s happening here? Because we added Spring Security into our build, Spring Boot has configured Spring Security for our use. The default behavior is to require basic auth for all endpoints. This is a good approach to secure everything by default, but it can trip you up if you’re not accustomed to working with Spring Security.

Spring Security Configuration

What we need to do, is tell Spring Security to allow all requests access to the root path. I’ll be covering Spring Security in additional detail in a future post,  but for now, we need to add a Spring Configuration class to allow us to configure Spring Security.


To accommodate the Spring Security configuration, I created a new package and added the SecurityConfiguration  class. By annotating the class with the @Configuration  annotation, I’m telling Spring this is a configuration class. When doing Java configuration for Spring Security, you need to extend the WebSecurityConfigurerAdapater  class and override the configure method.

Spring Boot and Package Scans

One quick note I want to call out here, the controller and configuration classes I’ve just defined are annotated Spring Components. Spring will only pick these up when their respective package is included in a component scan. A default behavior of Spring Boot when using the @SpringBootApplication annotation is to perform a package scan on its package (and all sub packages). Because my Spring Boot application resides in the package guru.springframework, the annotated Spring Components in the child packages are automatically found by Spring. If they were in a different package tree, I would need to explicitly tell Spring Boot to scan that package. This is important to know, and is something that could easily trip up a beginner with Spring Boot.

Example Web Page:

At this point in building our Spring Boot web application, we have not applied any styling to our Thymeleaf template file. Its pure simple, unstyled HTML.

unstyled spring boot web page

Managing Web Resources Under Spring Boot

At this point our Spring Boot Web application is working, in the sense it generate some HTML. But that’s not very realistic for today’s web applications. Any modern web application is going to have some web resources to manage. Web resources typically include:

  • CSS files.
  • Javascript assets
  • Images

Right now, our web page is very boring. Lets dress it up using Bootstrap CSS and JQuery.

Static Resources with Spring Boot

Spring Boot will automatically serve static resources from the path /resources/static. By a generally accepted convention, you will typically put CSS files in /resources/static/css, Javascript files in /resources/static/js, and images in resources/static/images. You could name the directories after /resources/static/ whatever you wish, this is just a convention you will likely see used and it helps you organize the static resources.

I like to add a CSS file for any overrides and customization I’ll need. I’m going to add an empty CSS file into /resources/static/css and then add it to the Thymeleaf template as follows:

Notice how the link tag has two href attributes? The first one in normal HTML will be used by the browser when the template is read from the file system. The second with the ‘th’ namespace is used by Thymeleaf when the template is rendered via Spring Boot. In this case a SPeL expression is being used to resolve the path of the static asset under Spring Boot, and this will be used as the path when the template is rendered by Spring Boot for the browser via a request through Tomcat.

This is what is meant when Thymeleaf is called a natural template engine. In this case, the CSS file is found for the HTML file via the relative path in the file system, then again when it’s deployed using a SPeL notation.

Spring Boot and WebJars

More than once I’ve copied all the files for Bootstrap CSS or JQuery into a resources folder, and then managed the lifecycle of their versions. This can be a manual and tedious process. WebJars is a very cool concept which which packages web assets into a JAR file for your use. The JAR s are available in public Maven repositories, making them build assets you can easily include in your project. (Did you know JAR files are just zip files, with the extension changed to JAR?)

Spring Boot supports WebJars out of the box. We just need to include the dependency in our Maven POM file for the project, then add it to our Thymeleaf template file.

We can declare the WebJar dependencies for Bootstrap CSS and JQuery by adding the following lines to our Maven POM file:

Now we can add the Bootstrap CSS and JQuery dependencies to our index.html file as follows:

Note: In this example I’m using a public CDN for the Bootstrap CSS and JQuery assets. By doing this I can preserve the natural templating of the Thymeleaf template file.

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

Styling Our Example

Now that we have the Bootstrap CSS and JQuery resources loading with our Spring Boot web application, lets add a little Bootstrap styling to our index.html file.


Example web page:

spring boot web page


At this point in this tutorial series on building a Spring Boot web application using Spring Boot, we’ve shown you how to create a basic project using the Spring Initializr and setup support for Thymeleaf. You can see how Spring Boot has made some common sense choices for us, like configuring the Thymeleaf template engine for use with Spring MVC, defaulting the locations for static resources, and providing out of the box support for WebJars.

In our next post on Spring Boot, we will take a look at setting up the persistence layer with Spring Boot, H2 and Spring Data JPA.

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.


I went through the content of this post on YouTube video. You can check it out below.



Spring Boot – Making Spring Fun Again

I’ve been playing around with Spring Boot again and really like what The Spring Team has been doing. Spring Boot is making Spring fun again. I haven’t had this much pleasure developing Spring Applications since I started learning Grails.

One of the things I loved about the Grails framework was its common sense approach to building web applications. Sure, Spring was under the covers of Grails. But the Grails team wired Spring up with a lot of defaults. For example, if you were using Hibernate to write to a database of course you’re going to want a Spring Transaction Manager.

Grails came out of the box with a transaction manager configured for you. If you were writing a Spring MVC application, you’d need to add a transaction manager into your configuration. The Spring Framework gives you all these pre-built components, but it was left up to you to wire them up into your application. You as the developer are responsible for everything. All the components are there, but some ‘assembly’ is required.

The cool part about Spring Boot is it makes a lot of common sense guesses for you. Like if you add Hibernate to your build, it guesses you’re going to want a transaction manager. The transaction manager is just one example of a common no-brainer Spring component you’d normally need to wire up that Spring Boot will automatically do for you. Spring Boot actually has over 200 default choices which it makes for you.

Spring Boot takes a lot of the mundane pain out of building Spring Applications. It really is making Spring Fun again. Spring Boot is still a newcomer in the family of Spring Projects. Even though Spring Boot is new, I think its the future of Spring application development.

Building a Spring Boot Web Application

Think about building a simple web application using Spring. You’re probably going to want to:

  • Use Spring of course!
  • Spring MVC for the web part.
  • Thymeleaf for the template engine, because you’re just plain tired of using JSPs.
  • Good ol’ Hibernate for your ORM.
  • An H2 database as your development database.
  • Spring Data to take the pain out of using Good Ol’ Hibernate.
  • Spring Security to secure your web application.
  • Tomcat as your application server.

In this Spring Boot tutorial I’m going to walk you through step by step in developing a web application using Spring Boot and the technologies I listed above.

Free Spring Tutorial
New to Spring? Checkout my free Introduction to Spring online course.

Getting Started with Spring Boot

I already created one ‘Getting Started with Spring Boot‘ post, but I’m going to walk through another example here. I want you to be able to follow through this Spring Boot tutorial step by step.

Creating the Spring Boot Project Using IntelliJ

The folks over at JetBrains have added some awesome support for Spring Boot in IntelliJ. This makes it very easy to create a Spring Boot based project using the IntelliJ IDE.

In the following video, I show you how to initialize a Spring Boot project with IntelliJ.

If you don’t have access to IntelliJ, you can always use the Spring Initializr to download a preconfigured Spring Boot project. Be sure to check the following options:

  • Security
  • Thymeleaf
  • Web
  • JPA
  • H2

Reviewing the Spring Initializr Artifacts

The project created by the Spring Initializer is a Maven project and follows the standard Maven directory layout. Below is a screen print from my IntelliJ IDE. There is one application class created for us, an empty properties file, a stub for a JUnit integration test, and the Maven POM file.
spring boot project structure


The Spring Initializer create us a very basic Spring Boot application class. Technically, this is a Spring Configuration class. The annotation @SpringBootApplication enables the Spring Context and all the startup magic of Spring Boot.


We’re also give a stub of a JUnit Integration test. Checkout this post if you’d like to learn more about Integration Testing with Spring and JUnit.


Here is the Maven POM file that the Spring Initializer created for us. This was customized for us based on the options we selected in the Spring Initializer. The presence of these dependencies is important because Spring Boot will make decisions on what to create automatically when certain things are found on the classpath. For example, you can see the dependency for the H2 database. Because this exists on the classpath when the application is run, Spring Boot will automatically create a data connection and an embedded H2 database.

Spring Boot Dependencies

What I found interesting about Spring Boot is how it manages dependencies. In the early days of Java development, you as the developer were required to manage all the dependencies. It was a very time consuming task. And led to a lot of errors. If you were using an open source library in your project, it was very easy to forget one of its dependencies, which could lead to runtime errors. In modern Java development this task of dependency management has been delegated to tools such as Maven.

Now when you define a dependency in Maven, Maven checks that artifacts dependencies, each of which can have its own set of dependencies, and so on. You can read more about dependency management in Maven here.

I’m impressed with how the Spring Boot team has leveraged the dependency management features of Maven (and Gradle) for Spring Boot. Prior to Spring Boot, when setting up a Spring Project, you needed to compose the Spring jars needed for your project. This was not always as straight forward as it sounds. The Spring Boot team has basically created Spring Boot POMs with bundled Spring dependencies.

You can use the Maven command of mvn dependency:tree to generate a report on the dependency tree. Running the command on this project produces the following dependency tree.

Here you can see how the top level Spring Boot starter dependencies listed in the Maven POM file call in their respective Spring components. Its a very simple idea, but very useful too. In days past, I can remember whenever starting a new Spring project spending a morning or so mucking around setting up the Maven Dependencies for the Spring components I was using.

Free Introduction to Spring Tutorial

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


In this post we’ve taken a look at using the Spring Initializer via IntelliJ to create a Spring Boot Project and examined the project files created by the Spring Initializer.

If you watched the video of me trying to run the Spring Boot application in IntelliJ, you saw the application fail because there were not Thymeleaf templates. In the next post of this tutorial series on Spring Boot, I’ll show you how to setup the Web Assets.

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.