How to build Rest Service with Spring Boot - A Step by Step Tutorial for Beginner - 2

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:

  1. Change the file name of application.properties to application.yml
  2. Add H2 configuration parameters to the file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

spring:
datasource:
driverClassName: org.h2.Driver
url: jdbc:h2:./hohistar-con-data
username: sa
password:
jpa:
database: H2
generate-ddl: true
show-sql: true
hibernate:
ddl-auto: create-drop
h2:
console:
enabled: true
path: /api/h2
settings:
web-allow-others: true

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Todo {


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;

private String title;

private String desc;

}

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
2
3
4
@Repository
public interface TodoRepository extends JpaRepository<Todo, Integer> {

}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class TodoBiz {

@Autowired
private TodoRepository todoRepository;

@Transactional
public void addTestTodos(List<Todo> todos) {

todos.forEach(o -> todoRepository.save(o));
}

@Transactional
public void addTodo(Todo todo) {

todoRepository.save(todo);
}

@Transactional
public List<Todo> listAll() {

return todoRepository.findAll();
}

}

Transform Api class

Open the TodoApi class, add a testAddTodos method, and save the Todo item in the database in the method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@RestController
public class TodoApi {

@Autowired
private TodoBiz todoBiz;

@GetMapping("/ok")
public String ok() {
return "ok";
}

@GetMapping("/todo")
public List<Todo> getTodoList() {

// List<Todo> todos = new ArrayList<>();
// todos.add(new Todo(1, "Call Metting", ""));
// todos.add(new Todo(2, "Print File", ""));
// return todos;

return todoBiz.listAll();
}

@GetMapping("/test/add/todos")
public String testAddTodos() {


List<Todo> todos = new ArrayList<>();
todos.add(new Todo(null, "Call Metting", ""));
todos.add(new Todo(null, "Print File", ""));

todoBiz.addTestTodos(todos);

return "ok";

}

@PostMapping("/todo")
public String addTodo(@RequestBody Todo todo) {

todoBiz.addTodo(todo );

return "ok";
}

}

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
2
3
4
5
6
...
Hibernate: drop table if exists todo CASCADE
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table todo (id integer not null, desc varchar(255), title varchar(255), primary key (id))
...

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.

  1. 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
2
3
4
ibernate: call next value for hibernate_sequence
Hibernate: call next value for hibernate_sequence
Hibernate: insert into todo (desc, title, id) values (?, ?, ?)
Hibernate: insert into todo (desc, title, id) values (?, ?, ?)
  1. 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_
  1. 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.

本文标题:How to build Rest Service with Spring Boot - A Step by Step Tutorial for Beginner - 2

文章作者:Morning Star

发布时间:2021年07月10日 - 10:07

最后更新:2022年01月21日 - 09:01

原始链接:https://www.mls-tech.info/java/springboot-rest-api-tutorial-2-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。