Spring Boot: H2 DB and Thymeleaf

Spring Boot

Spring-Boot
project
maven
thymeleaf
db
h2
Spring Boot
Author

albertprofe

Published

Tuesday, June 1, 2021

Modified

Friday, November 1, 2024

📘 Create a Spring Boot Project

  1. Create a Maven Spring Project
  2. Install H2 DB
  3. Define Application.properties
  4. Create Model: @Entity Book and JPA @Repository
  5. Create @Controller and @Service
  6. Create HTML template with Thymeleaf

1 Maven Project

Be careful with this.

Compatibility matrix Java / JPA / ORM Hibernate / Jakarta

Compatibility matrix Java / JPA / ORM Hibernate / Jakarta

1.1 POM.xml and dependencies

Check the base project, Library5.

POM.xml and dependencies: The POM.xml file manages the dependencies of a project in Maven.

  • The first two dependencies, spring-boot-starter-thymeleaf and spring-boot-starter-web, are starter dependencies for Spring Boot and include libraries for building web applications using the Thymeleaf template engine.
  • The spring-boot-devtools dependency provides development-time tools to improve the development experience, such as automatic application restarts and enhanced debugging capabilities.
  • javafaker is a library used to generate random data for testing purposes, and lombok is a library that simplifies Java code by reducing boilerplate code.
  • The spring-boot-starter-test dependency includes the necessary libraries for testing Spring Boot applications, and the junit-jupiter-api dependency provides the JUnit 5 testing framework.
  • The spring-boot-starter-jdbc and spring-boot-starter-data-jpa dependencies provide libraries for accessing and manipulating databases in a Spring Boot application.
  • Finally, the h2 dependency is a lightweight in-memory database used for testing and development purposes.

The groupId and artifactId attributes uniquely identify each dependency, while the version attribute specifies the version of the library to use.

The scope attribute defines the visibility of the dependency at different stages of the application’s lifecycle, and the optional attribute indicates that the dependency is not strictly required for the application to function.

2 Model

2.1 @Entity book

A persistence entity is a lightweight Java class with its state typically persisted to a table in a relational database.

Entity definition
  • Instances of such an entity correspond to individual rows in the table.

  • Entities typically have relationships with other entities, and these relationships are expressed through object/relational mapping (ORM) metadata.

  • This metadata may be specified directly in the entity class file by using annotations (or in a separate XML descriptor file distributed with the application).

DemoApplication.java
@Getter @Setter @NoArgsConstructor @AllArgsConstructor
@Entity(name="Book")
@Table(name="BOOK_TABLE")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="BOOK_ID")
    private long bookId;
    @Column(name="BOOK_TITLE")
    private String title;
    @Column(name="AUTHOR")
    private String author;
    private int pages;
    @Column(name="PUBLISHED_YEAR")
    private int publishedYear;
    @Column(name="ISBN")
    private String isbn;
}
Historical note

Spring MVC was the original web framework in the Spring ecosystem, and it relied heavily on XML-based configuration.

Over time, Spring MVC evolved to become more annotation-driven, which made it simpler and more concise to work with.

With the advent of Spring Boot, the Spring ecosystem became even more streamlined, with convention-over-configuration and a focus on out-of-the-box features that made it easier to build and deploy Spring-based applications.

In the domian of database access, Spring evolved from using plain JDBC to providing support for Object-Relational Mapping (ORM) frameworks such as Hibernate and JPA.

Spring also provides transaction management capabilities through the Spring Transaction module, which allows developers to define transaction boundaries declaratively using annotations or XML configuration.

By using Spring, developers can build robust, scalable, and maintainable web applications that leverage modern technologies and best practices.

2.2 H2 DB creation: step-by-step

  1. Download the H2 database: Go to the H2 database website at H2 DB{external} and download the latest version of the H2 database for Linux. You can download either the ZIP or the TAR package.

  2. Extract the downloaded file: Open the terminal and navigate to the folder where you downloaded the H2 database.Extract the contents of the downloaded file using the following command:

linux.sh
tar -zxvf h2-*.tar.gz
  1. Start the H2 database server: Navigate to the H2 database directory and start the H2 database server by running the following command:
linux.sh
java -jar h2*.jar
linux.sh
cd <download directory>
unzip h2*.zip
cd h2/bin
chmod +x h2.s

This will start the H2 database server and display the URL where the H2 database can be accessed.

  1. Connect to the H2 database: Open a web browser and enter the URL displayed in the terminal. The H2 database web interface will open in the browser.

    • Other option is to execute the app and then clik “Create a new database” from the H2 Icon

  1. Create a new database: In the H2 database web interface, click on the “Create a new database” button and follow the prompts to create a new database.

Create H2 DataBase: define parameters

Create H2 DataBase: define parameters

Create H2 DataBase: DB created

Create H2 DataBase: DB created

Create H2 DataBase: check it has been created

Create H2 DataBase: check it has been created

Create H2 DataBase: connect to DB

Create H2 DataBase: connect to DB

Name your database: jdbc:h2:/home/albert/MyProjects/MyDBs/h2DBs/myDB

  1. Connect to the new database: Once the new database is created, click on the “Connect” button in the H2 database web interface and introduce the right parameters.
Important

Saved Settings: Generic H2 (Server)
Setting Name: Generic H2 (Server)

Driver Class: org.h2.Driver
JDBC URL: jdbc:h2:/home/albert/MyProjects/MyDBs/h2DBs/myDB

User Name: albert
Password: ••••

Create H2 DataBase

Create H2 DataBase
  1. Use the H2 database: Now you can start using the H2 database. You can create tables, insert data, and perform queries using SQL commands.

2.3 JPA

JPA: Jakarta Persistence, formerly Java Persistence API

JPA definiton

JPA is a application programming interface specification that describes the management of relational data.


DemoApplication.java
public interface BookRepository extends CrudRepository<Book, Long> {}

This code is defining a Java interface named BookRepository that extends the CrudRepository interface.

Crud Repository

The CrudRepository interface is a built-in interface in the Spring Framework that provides generic CRUD (Create, Read, Update, Delete) operations for working with entities in a database.

The BookRepository interface is being used to define a repository for managing Book entities, where Book is likely a Java class representing a book object in the application.

The Long parameter in CrudRepository<Book, Long> specifies the type of the primary key for the Book entity. In this case, the primary key is a Long type.

By extending CrudRepository, the BookRepository interface will inherit methods such as save(), findById(), findAll(), and deleteById(), among others, which can be used to perform database operations on Book entities.

This allows for efficient and standardized data access and management within the application. Otherwise, we should use a DAO:

The public keyword specifies that the interface can be accessed from other classes, and the interface name should be in camelCase to follow Java naming conventions.

2.4 Application.Properties

Application.Properties: the application.properties file contains configuration properties for a Spring Boot application.

#H2 DATASOURCE
spring.datasource.url=jdbc:h2:tcp://localhost/~/dataBaseH2/library5
spring.datasource.username=albert
spring.datasource.password=1234
spring.datasource.driver-class-name=org.h2.Driver

#JPA
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

3 Controller

3.1 @Controller Web

DemoApplication.java
@Controller
@RequestMapping("/library")
public class LibraryWebController {

    @Autowired
    BookService bookService;

    @RequestMapping("/books")
    public String getWeb(Model containerToView) {
        //
        containerToView.addAttribute("booksfromController",
                bookService.getAllBooks());
        

        return "showBooks";
    }
}


The method getWeb() is handling a GET request to the “/library/booksURL path and adding a list of books retrieved from the BookService to the Model attribute “booksfromController”.

@controller and View are connected by HTML/ViewResolver/TH

@controller and View are connected by HTML/ViewResolver/TH

Finally, it returns the name of the view that will be used to render the response.

getWeb method

getWeb method
  1. Java Class and annotations:
    • @Controller: This is an annotation that identifies the class as a Spring MVC controller.
    • @RequestMapping("/library"): This annotation maps the controller to the URL path "/library".
  2. @Autowired BookService bookService;: This annotation injects an instance of the BookService into the controller.
  3. @RequestMapping("/books"): This annotation maps the method to the URL path "/library/books".
  4. public String getWeb(Model containerToView): This is the method declaration for the GET request handler.
  5. containerToView.addAttribute("booksfromController", bookService.getAllBooks());: This adds a list of books retrieved from the BookService to the model attribute "booksfromController".
  6. return "showBooks;: This returns the name of the view that will be used to render the response.

4 View: Thymeleaf

In Spring Boot, the @Controller returns the name of the HTML file (also known as the view) that should be rendered to display the response.

The view is then resolved by the ViewResolver and the corresponding HTML template file is located.

The data that the @Controller wants to send to the view is stored in a Model object. The Model object is passed to the view as a parameter and can be accessed from the HTML template.

Thymeleaf

Using template engines like Thymeleaf, the view can then use expressions and tags to inject the data from the Model object into the HTML file.

FreeMarker. Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.

Finally, the rendered HTML file with the injected data is sent as the response to the client’s request.

Thyemeleaf builds the HTML table injecting data from Model object. This model objects comes from @Controller.

It builds a <table></table> with a header and multiple rows <tr></tr>

[1] A java forEach wirtten in Thymeleaf iterates over a list of books booksfromController using the trth:each attribute.

Scope in Thymeleaf

The th:each attribute on <tr> scope starts in <tr> and finishes in </tr>

[2] For each book, it creates a table cell <td> and displays different attributes of the book, such as bookId, title, isbn, pages, publishedYear, and author.

There are also three links in the row, each represented by an anchor <a> tag.

These links use Thymeleaf’s URL syntax @{...} to generate URLs that invoke Spring MVC @Controller methods.

[3] [4] [5] The deleteBook(), updateBook(), and detailBook() methods will be called with the bookId parameter set to the book.bookId value of the cu Open a web browser and enter the URL dirrent iteration.

The links are styled using CSS classes from the W3.CSS framework.

5 Example: Library5

5.0.1 Tree-folder Project root

Collapsed tree-folder:

  1. scr/main: This directory contains two subdirectories - java and resources - which respectively hold the Java source code and resource files for the application.
    • java
    • resources
  2. scr/test: This directory contains unit test code and resources that can be used to test the application.
  3. target and files:
    • target: This directory is the output directory where compiled classes and artifacts are stored.
    • files on root: This directory holds any additional files or resources needed by the application that are not directly related to the code or tests: POM.xml is the most important.

5.0.2 Tree-folder Project

All files in our tree-folder:

The Spring Boot tree-folder structure includes various components such as POM.xml, Git, Java classes, application.properties, and HTML templates that help manage dependencies, version control, database access, configuration, and dynamic content generation.

  1. POM.xml and dependencies: The POM.xml file manages the dependencies of a project in Maven.
  2. Git and .gitignore: Git is a version control system that helps manage code changes, while .gitignore is a file that specifies which files and directories should be excluded from version control.
  3. Main: The main method is the entry point for a Java application, where the program starts execution.
  4. Java Classes:
    • @Entity: A Java class annotated with @Entity is mapped to a database table.
    • @Controller: A Java class annotated with @Controller handles incoming web requests and returns a response.
    • @Repository: A Java class annotated with @Repository provides database access to other classes in the application.
  5. Application.Properties: The application.properties file contains configuration properties for a Spring Boot application.
  6. Templates HTML: HTML templates are used in a web application to generate dynamic content on the server-side.

6 Execution

Web client from Chrome web browser makes a request to Spring Boot Server

Web client from Chrome web browser makes a request to Spring Boot Server

Spring Boot Server gets the request and manages to create a Response to client in HTML file format

Spring Boot Server gets the request and manages to create a Response to client in HTML file format

6.1 Auto-reload compiler

Spring Boot Dev Tools

Any changes to views or resources can be seen in the browser directly, no need restarts, just refresh the browser. As wwll, any changes to the code that will restart the Spring container automatically.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

Auto-reload compiler: Advanced Settings

Auto-reload compiler: Advanced Settings

Auto-reload compiler: build project automatically

Auto-reload compiler: build project automatically

Enable this option: compiler.automake.allow.when.app.running

Enable this option: compiler.automake.allow.when.app.running

In Menu -> Build -> Build Project CTRL + F9

Back to top