In this series of , I showed you how to build a most basic and simple Rest API with Spring Boot. This time we continue to go deeper and add database functionality to the application.
Configuration Database
In order to simplify the case, we use pure Java database H2, which needs to be configured as follows:
- Change the file name of application.properties to application.yml
- Add H2 configuration parameters to the file
1 |
|
Note: The database will be automatically generated in the project root directory
Add JPA annotations to entity classes
We added two new annotations to the entity class: “@NoArgsConstructor” and “@Entity”, and annotated the id attribute as the primary key.
1 |
|
Add Repository class
Add a repository package to the project, and create a new interface: TodoRepository in the package, which inherits from JpaRepository. And add @Repository annotation to the definition of the interface.
1 |
|
Define business class
Add a new biz package, and create a new business class in the package: TodoBiz. This class is a simple Java class, but with the @Service annotation added, an instance of TodoRepository is injected into the class.
1 | public class TodoBiz { |
Transform Api class
Open the TodoApi class, add a testAddTodos method, and save the Todo item in the database in the method.
1 |
|
Note: The business object TodoBiz is injected into the Api
Run to view the results
Run the program, you can see this output in the console:
1 | ... |
Note Spring Data JPA has automatically established a database and corresponding table structure for the project based on the configuration information.
Then, let us manipulate the data through the API.
- Visit localhost:8080/test/add/todos in the browser once, and return the “ok” string
You can see the following output in the console:
1 | ibernate: call next value for hibernate_sequence |
- Visit localhost:8080/todo to view the data inserted into the database through step 1.
You can see the following output in the console:
1 | Hibernate: select todo0_.id as id1_0_, todo0_.desc as desc2_0_, todo0_.title as title3_0_ from todo todo0_ |
- View the data in the database in localhost:8080/api/h2
Next Step
In , we will introduce how to get Todo data from the database.