前言
之前已经讲过了一些关于MyBatis-plus的知识,大家有兴趣的话,可参考一下文章
SpringBoot(40) — SpringBoot整合MyBatis-plus
SpringBoot(41) — MyBatis-plus常用查询
SpringBoot(42) — MyBatis-plus查询数据表中一列数据的部分字段
SpringBoot(43) — MyBatis-plus一些特殊查询
SpringBoot(44) — MyBatis-plus自定义sql查询
SpringBoot(45) — MyBatis-plus分页查询
SpringBoot(46) — MyBatis-plus更新数据
SpringBoot(47) — MyBatis-plus删除数据
SpringBoot(48) — MyBatis-plus基本配置
今天就让我们来学习下MyBatis-plus在项目架构方面的处理——通用service
今天涉及知识有:
-
SpringBoot项目架构回顾 - 通用
service建设
2.1 先在 entity 层提供映射数据表的实体类
2.2 通用 service 建设 - 增加通用
service后的调用变更
3.1 使用通用 service 前的数据库操作
3.2 使用通用 service 后的数据库操作 - 利用通用
service进行数据操作
4.1 前期准备
4.2 批量添加数据
4.3 批量添加或更新
4.4 删除数据
4.5 修改数据
4.6 查询单条数据
4.7 批量查询 - 项目结构图
一. SpringBoot 项目架构回顾
在我们开发SpringBoot项目时,我们经常会涉及到以下几部分:
- controller
- service
- dao
- entity
一般entity包下存储将数据表数据映射出来的实体类。dao包下是操作数据库的方法类,service包下处理业务逻辑,controller包下提供对外发布api。
之前我们讲到的MyBatis-plus对数据库的各种操作都是在dao包层面上进行的,即操作方法都是写在dao包下的类中,但是一般都是service包下类调用dao包下的类,如果业务逻辑比较简单的话,势必出现在在dao层写过一个方法,然后在service又要写一个类似的,显得重复而臃肿。这时,我们就可以利用MyBatis-plus的通用service直接将数据操作的逻辑在service下处理掉,省去了dao层和service做重复操作的麻烦。
二. 通用 service 建设
2.1 先在 entity 层提供映射数据表的实体类
下面贴出 数据库表 test_pro.demo对应的映射实体Student代码:
@Data
@Component("Student")
@TableName(value = "demo")
public class Student {
//主键自增
@TableId(value = "id",type = IdType.AUTO)
private int id;
@TableField(value = "name",condition = SqlCondition.LIKE) //表属性
private String name;
@TableField(value = "age") //表属性
private int age;
}
2.2 通用 service 建设
项目dao层下,新建StudentMapper接口类继承自MyBatis-plus的BaseMapper,然后泛型中填test_pro.demo映射的实体类Student。StudentMapper代码如下: