Spring Boot with Thymeleaf tutorial, part 3 – Spring Data JPA

In this tutorial I am going to add a possibility of storing added posts in a database. I extend previous project where post form is already implemented. I use H2 in-memory database to simplify project’s complexity. To implement data access layer in the application I use Spring Data JPA.

1. Set up the project as is described in previous post or checkout the source code.

2. Add Maven dependencies to enable Spring Data JPA and H2 database:

pom.xml should look like this:

 

3. Create business domain object PostEntity. This object will be stored in database by JPA. It is very similar to Post object in form package, but has additional JPA annotations like @Entity, @Id, @GeneratedValue and id field. I have decided to split it into two objects. It would be also possible use only one Post object, but then the file could look unreadable.

 

4. The repository class is needed to manipulate (read, save, update, delete) on domain objects. Using Spring Data it is very easy to create simple repository interface by extending CrudRepository class from Spring Data. By default there are enabled number of common functions, but it is also possible to create own functions, like findByTitle(String title) in example below. The only thing what is needed to do is defining functions according to Spring Data rules. More informations about Spring Data you can find here.

 

5. Right now we can use the repository in our other classes. PostRepository is used in Home controller for storing in database post passed in form and getting all posts from database to show them on results view. Spring can automatically find it out if we use @Autowired annotation. Functions postRepository.findAll() and postRepository.save() are inherited from CrudRepository, so we had not to implement them.

 

6. The last thing which has to be realized is a view where all posts from the database can be displayed. We can modify result.html file to let Themeleaf template engine to iterate over collection of posts. It is very simple in Thymeleaf and implementation can look like this:

 

All file structure should look like this:

05-file_structure

Compile the application by

mvn package

and run it by

java -jar target/spring-boot-thymeleaf-jpa-0.0.1.jar

Your application is available on http://localhost:8080 and all posts can be displayed on http://localhost:8080

05-result

Complete source code: https://github.com/jvmhub/Spring-Boot-with-Thymeleaf-part-3-Spring-Data-JPA