接上一节,SpringBoot连接数据库。

设计操作数据库的API,让数据库操作更加便捷。

设计Restful API

请求方式 路径 功能
GET /users 获取所有用户信息
GET /users/{id} 查询单条记录
POST /adduser 创建一条用户记录
PUT /users/{id} 更新单条记录

创建数据库接口

UserRepository.java

  • 继承JpaRepository接口
  • 可以自定义一些方法。此处我选择直接使用继承的方法,就不写其它东西了。
1
2
3
4
5
6
7
package com.mysqlapi;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository{

}

JpaRepository接口类

这个接口又继承了ListCrudRepository<T, ID>ListPagingAndSortingRepository<T, ID>

这些接口为我们封装了很多方法。具体请创建之后,点进去查看。

image-20230310192452411

image-20230310192534454

image-20230310192606010

image-20230310192546820

image-20230310192728513

image-20230310192652324

完善Controller

UserController.java

+查询记录

+增加记录

+删除记录

+更改记录

  • 初始化接口
  • 添加注解@Autowired
  • 添加@GetMapping、@PostMapping等,实现对应的接口方法
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.mysqlapi;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
@Autowired
private UserRepository repository;

// 获取所有记录
@GetMapping("/users")
public List<User> getAll() {
return repository.findAll();
}

// 查询单条记录
@GetMapping("/users/{id}")
public User findById(@PathVariable("id") Integer id) {
return repository.findById(id).orElse(null);
}

// 添加一条记录
@PostMapping("/adduser")
public User addUser(@RequestParam("usrn") String usrn, @RequestParam("pswd") String pswd, @RequestParam("role") String role) {
User user = new User();
user.setUserName(usrn);
user.setPassword(pswd);
user.setRole(role);
return repository.save(user);
}

// 修改一条记录
@PutMapping("/users/{id}")
public User updateUser(@PathVariable("id") Integer PathId, @RequestParam("id") Integer id, @RequestParam("usrn") String usrn, @RequestParam("pswd") String pswd, @RequestParam("role") String role) {
Optional<User> optional = repository.findById(id);
User user = new User();
// 是否存在该用户,不存在则返回null
// 方法一(推荐)
optional.orElse(null);
//// 方法二
// if(optional.isPresent()) {
// user=optional.get();
// }else {
// return null;
// }
if (id.toString()!= null&&id.toString()!="") {
user.setId(id);
} {
user.setId(optional.get().getId());
}
if (usrn != null&& usrn!="") {
user.setUserName(usrn);
}else {
user.setUserName(optional.get().getUserName());
}
if (pswd != null&& pswd!="") {
user.setPassword(pswd);
}else {
user.setPassword((optional.get().getPassword()));
}
if (role != null&& role!="") {
user.setRole(role);
}else {
user.setRole(optional.get().getRole());
}
return repository.save(user);
}
}

如果在这一步结束,能成功运行吗?

答案是报错java.lang.IllegalArgumentException: Could not resolve domain type of interface com.mysqlapi.UserRepository,为什么呢?原因是继承jpaRepository时未指定两个类型,即<对应实体类,主键的数据类型>

修改UserRepository.java

1
2
3
4
5
6
7
package com.mysqlapi;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User,Integer>{

}

执行程序

run as spring boot app

当前的程序还是存在问题,使用PUT更新记录时,当id空(非null)时,会报错;当某个参数null时,仍然报错(似乎!=null语句未生效)。思考为什么会发生这种问题?如何解决?

数据库中`_sequence`表的作用

该表指定了下一个记录的自增值。用next_val字段表示。如果使用接口插入数据失败,有可能是这里出错,日志中会报错Duplicate entry 'xxx' for key 'xxx.PRIMARY'。只需要修改一下自增值即可。

处理数据库乱码问题

统一项目和数据库中使用的编码。

数据库连接时设置编码

1
url=jdbc:mysql://localhost:3306/managerSys?useUnicode=true&characterEncoding=utf8