Hi All,

Greeting of the day!

Today we will be building Spring MVC CRUD application using spring boot and Thymeleaf, so let's start.

First, we will create a basic project structure using Spring initializr and will add the below dependency.

 

Additionally, we will add oracle dependency in pom.xml

<dependency>
<groupId>oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency> 
So below will be complete pom.xml

In the end, we will have below project structure


Now add below database-related properties in the application.properties

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.hibernate.ddl-auto=update

Now we will create a model class Book for our application which will be mapped to a database table.

Now table will be created automatically as we have mentioned spring.jpa.hibernate.ddl-auto=update in the application.properties.

We need to create a sequence in oracle which we have mentioned in Book.java.And for that, we need to execute the below scripts 

Create sequence book_id_sequence;

Now we will create a repository layer for our application using JpaRepository.
Now let's create a service layer, where you can add your business logic and code to manage transactions.

Now we will create Controller i.e BookController.java, here we will create methods to handle 
redirections, along with operations to create, edit, view, and update.

For display purposes, we are using Thymeleaf. So from the controller, we will return the name of the page which will be under resources/templates for the view layer.

After adding, updating & deleting the book we have called redirect for viewbook. 

For displaying data in view page using thymeleaf we will set data in model 
eg model.addAttribute("books",books);


Lastly, we will create an HTML page for adding and viewing books. We are using add_book.html for both adding and editing books.

So let's create add_book.html for adding and editing the book

Now we will create view_books.html under templates folder for viewing books that we have added. As we have set list of books to books mode attribute in controller using model.addAttribute("books",books);
We will iterate over books variable using th:each as shown below to create new row for each book.

So congratulations you have completed the sample CRUD application using spring MVC and spring boot.
Below is output



Also, you can refer to CRUD examples






 
Thanks
Happy Learning!