SpringBoot编写接口(需要mybatis-plus)

项目文件夹名称

新建的项目在/src/java/com.你的项目名字/新建四个Package文件夹分别叫 controller,Mapper,entry,service

controller:控制层 ,dao(mapper):数据层,service:服务层,domain/entity:实体类

导包

lombok坐标

作用: 可以不需要写Getter与Setter方法,也不用写有参和无参构造器

1
2
3
4
5
6
7
8
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>

Mybatis-plus

可以简化的操作数据库,不需要写MySQL语句

1
2
3
4
5
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>

编写application

在项目文档中,打开 /src/resources/application.yml配置文件

1
2
3
4
5
6
7
8
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&useSSl=false&serverTimezone=UTC
username: root
password: 123456

编写实体类

在entry文件夹下,创建一个实体类,名称为User.java。注:名称也可以为个人所需要编写的实体类。

@TableId注解是专门用在主键上的注解,如果数据库中的主键字段名和实体中的属性名,不一样且不是驼峰之类的对应关系,可以在实体中表示主键的属性上加@Tableid注解,并指定@Tableid注解的value属性值为表中主键的字段名既可以对应上。

1
2
3
4
5
6
7
8
9
10
@Data
@AllArgsConstructor //有参构造器注解
@NoArgsConstructor //无参构造器注解
public class User {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String email;
private String phone;}

编写Mapper/Dao接口

Mapper文件夹下,新建接口,名字为UserMapper

注意:名字也可以为个人所需要编写的接口名称。代码中T为实体类

1
2
3
@Mapper
public interface UserMapper extends BaseMapper<T> {
}

在service文件夹下新建一个Package,名称为impl

impl文件夹下新建一个名为UserServiceimpl.java类 名字按个人所需要去编写

注意:千万不要忘记@Service 代码中的M为 Mapper下的接口名称 ,T为实体类。Service为service文件夹下的接口

1
2
3
@Service
public class UserServiceImpl extends ServiceImpl<M, T> implements Service {
}

编写Service

在service文件夹下,新建一个叫UserService的接口 注:名称可以按个人所需求的名字写

1
2
public interface UserService extends IService<T> {
}

注意: 代码中的T为实体类

编写Controller

在Controller文件下创建三个.java类 分别为Code、Result、StudentController

注意:类名称可以按照个人需求命名

第一步:编写Result.java

以下数据给StudentController.java 用于调用

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
public class Result {

private Integer code;
private Object data;
private String msg;

public Result(Integer code, Object data) {
this.code = code;
this.data = data;
}

public Result(Integer code, Object data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

第二步:编写Code.java

什么是final

finaljava中的一个关键字,意思为恒定不变。 java中final数据具体有两个含义:1、对于基本数据类型,表示永不改变的编译时常量;2、对于普通对象,表示该引用恒定不变不能指向另外一个对象,但是该对象本身是可以进行修改的。

以下代码用于在StudentController.java中用于输出。例如:添加成功输出20001 否则输出2002

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Code {
public static final Integer INSERT_OK = 20001;
public static final Integer INSERT_ERR = 20002;

public static final Integer UPDATE_OK = 20011;
public static final Integer UPDATE_ERR = 20012;

public static final Integer DELETE_OK = 20021;
public static final Integer DELETE_ERR = 20022;

public static final Integer SELECT_OK = 20031;
public static final Integer SELECT_ERR = 20032;
}

第三步:编写StudentController.java

说明:

@RestController为开发提供了方便,在提供json接口时需要的配置操作再也不需要自己配置了。

@RequestMapping表示共享映射,如果没有指定请求方式,将接收GETPOSTHEADOPTIONSPUTPATCHDELETETRACECONNECT所有的HTTP请求方式

@Autowired 可以对类成员``变量方法构造函数进行标注,完成自动装配的工作

@GetMapping,处理get请求
@PostMapping,处理post请求
@PutMapping,处理put请求
@DeleteMapping,处理delete请求

@RequestBody:主要用来接收前端传递给后端的json字符串中的数据的

@PathVariable :通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过

  • 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
  • 泛型 T 为任意实体对象
  • 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类
  • 对象 Wrapper条件构造器
1
2
3
4
5
@RestController
@RequestMapping("/students")
public class StudentController2 {
@Autowired
private StudentService2 studentService;}

增加数据

1
2
3
4
5
6
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);

使用:

1
2
3
4
5
@PostMapping
public Result save(@RequestBody Student student){
boolean flag = studentService.save(student);
return new Result(flag? Code.INSERT_OK: Code.INSERT_ERR, flag);
}

参数说明

类型 参数名 描述
T entity 实体对象
Collection entityList 实体对象集合
int batchSize 插入批次数量

原来没添加时的数据:

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
//原来版本
{
"code": 20031,
"data": [
{
"id": 1,
"username": "阿符123",
"password": "123456",
"email": "fantasy@777nx.cn",
"phone": "17812345678"
},
{
"id": 2,
"username": "老蔡",
"password": null,
"email": "lc@qq.com",
"phone": null
},
{
"id": 3,
"username": "老刘",
"password": null,
"email": "ll@qq.com",
"phone": null
}
],
"msg": "查询成功"
}

使用Postman测试接口运用添加后可以看到以下效果:

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
{
"code": 20031,
"data": [
{
"id": 1,
"username": "阿符123",
"password": "123456",
"email": "fantasy@777nx.cn",
"phone": "17812345678"
},
{
"id": 2,
"username": "老蔡",
"password": null,
"email": "lc@qq.com",
"phone": null
},
{
"id": 3,
"username": "老刘",
"password": null,
"email": "ll@qq.com",
"phone": null
},
{
"id": 4,
"username": "张三",
"password": null,
"email": "123@qq.com",
"phone": null
}
],
"msg": "查询成功"
}

删除数据

1
2
3
4
5
6
7
8
// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);

使用:

1
2
3
4
5
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
boolean flag = studentService.removeById(id);
return new Result(flag? Code.DELETE_OK: Code.DELETE_ERR, flag);
}

参数说明

类型 参数名 描述
Wrapper queryWrapper 实体包装类 QueryWrapper
Serializable id 主键 ID
Map columnMap 表字段 map 对象
Collection<? extends Serializable> idList 主键 ID 列表

Update 修改数据

1
2
3
4
5
6
7
8
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

使用:

1
2
3
4
5
@PutMapping
public Result update(@RequestBody Student student){
boolean flag = studentService.updateById(student);
return new Result(flag? Code.UPDATE_OK: Code.UPDATE_ERR, flag);
}

参数说明

类型 参数名 描述
T entity 实体对象
Wrapper updateWrapper 实体对象封装操作类 UpdateWrapper
Collection entityList 实体对象集合
int batchSize 插入批次数量

原本没修改前的数据:

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
{
"code": 20031,
"data": [
{
"id": 1,
"username": "阿符123",
"password": "123456",
"email": "fantasy@777nx.cn",
"phone": "17812345678"
},
{
"id": 2,
"username": "老蔡",
"password": null,
"email": "lc@qq.com",
"phone": null
},
{
"id": 3,
"username": "老刘",
"password": null,
"email": "ll@qq.com",
"phone": null
},
{
"id": 4,
"username": "张三",
"password": null,
"email": "123@qq.com",
"phone": null
}
],
"msg": "查询成功"
}

使用Postman测试接口运用修改把原本的张三修改为王五可以看到以下效果:

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
{
"code": 20031,
"data": [
{
"id": 1,
"username": "阿符123",
"password": "123456",
"email": "fantasy@777nx.cn",
"phone": "17812345678"
},
{
"id": 2,
"username": "老蔡",
"password": null,
"email": "lc@qq.com",
"phone": null
},
{
"id": 3,
"username": "老刘",
"password": null,
"email": "ll@qq.com",
"phone": null
},
{
"id": 4,
"username": "王五",
"password": null,
"email": "123@qq.com",
"phone": null
}
],
"msg": "查询成功"
}

查询数据(查询一条数据)

1
2
3
4
5
6
7
8
9
10
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

使用:

1
2
3
4
5
6
7
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id){
Student student = studentService.getById(id);
Integer code = student != null? Code.SELECT_OK: Code.SELECT_ERR;
String msg = student != null? "查询成功": "查询失败";
return new Result(code, student, msg);
}

参数说明

类型 参数名 描述
Serializable id 主键 ID
Wrapper queryWrapper 实体对象封装操作类 QueryWrapper
boolean throwEx 有多个 result 是否抛出异常
T entity 实体对象
Function<? super Object, V> mapper 转换函数

查询所有数据

List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查询所有列表
List<Map<String, Object>> listMaps();
// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查询全部记录
List<Object> listObjs();
// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

使用:

1
2
3
4
5
6
@GetMapping
public Result getAll(){
List<Student> list = studentService.list();
Integer code = list != null? Code.SELECT_OK: Code.SELECT_ERR;
String msg = list != null? "查询成功": "查询失败";
return new Result(code, list, msg);}

参数说明

类型 参数名 描述
Wrapper queryWrapper 实体对象封装操作类 QueryWrapper
Collection<? extends Serializable> idList 主键 ID 列表
Map columnMap 表字段 map 对象
Function<? super Object, V> mapper 转换函数