5、SpringBoot整合之SpringBoot整合MybatisPlus
springboot整合mybatisplus
目录(可点击直接跳转,但还是建议按照顺序观看,四部分具有一定的关联性):
首先给出四部分完整的项目结构
一、实现基础的增删改查功能
1.创建项目、选择依赖
选择spring web、jdbc api、mybatis framework、mysql driver
2.在pom文件中引入相关依赖
<dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <!-- 修改jdbc版本 --> <version>5.1.47</version> <scope>runtime</scope> </dependency> <!-- 引入mybatisplus的启动器 --> <dependency> <groupid>com.baomidou</groupid> <artifactid>mybatis-plus-boot-starter</artifactid> <version>3.3.2</version> </dependency> <!-- 引入lombok --> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> </dependency> <!-- 引入druid连接池 --> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>1.2.6</version> </dependency> <!-- 引入log4j --> <dependency> <groupid>log4j</groupid> <artifactid>log4j</artifactid> <version>1.2.17</version> </dependency>
3.建库、建表、插入数据
create database db_mybatisplus; use db_mybatisplus; create table tab_teacher( pk_teacher_id int primary key auto_increment comment '老师主键id,起始为1', teacher_name varchar(10) comment '老师姓名', teacher_sex char(1) comment '老师性别', teacher_salary double(6,1) comment '老师工资' ); -- 反复执行多次,随机插入多条数据 insert into tab_teacher values( null, substr(md5(rand()), 1, 5), if(rand()>0.5, '男', '女'), rand()*10000+1000 ); select * from tab_teacher;
4.配置核心配置文件
# 配置连接数据库的四大参数 spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.url=jdbc:mysql://192.168.133.139/db_mybatisplus?useunicode=true&characterencoding=utf8&autoreconnect=true&allowmultiqueries=true spring.datasource.username=root spring.datasource.password=root # 指定连接池的类型 spring.datasource.type=com.alibaba.druid.pool.druiddatasource # 显示sql语句 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.stdoutimpl
5.创建实体类
package cn.byuan.entity; import com.baomidou.mybatisplus.annotation.idtype; import com.baomidou.mybatisplus.annotation.tablefield; import com.baomidou.mybatisplus.annotation.tableid; import com.baomidou.mybatisplus.annotation.tablename; import lombok.allargsconstructor; import lombok.data; import lombok.noargsconstructor; import lombok.experimental.accessors; import java.io.serializable; @noargsconstructor// 创建无参的构造方法 @allargsconstructor// 创建满参的构造方法 @accessors(chain = true)// 使用链式方法 @data// 重写tostring方法等方法 @tablename("tab_teacher")// 对应表名 public class teacher implements serializable { @tableid(value = "pk_teacher_id", type = idtype.auto)// 主键必须有tableid注解 private integer teacherid; @tablefield("teacher_name") private string teachername; @tablefield("teacher_sex") private string teachersex; @tablefield("teacher_salary") private double teachersalary; }
6.创建teacher类的dao接口,继承basemapper接口,使用basemapper接口的方法
这里我省去了mapper层,直接让dao层接口继承basemapper
这里要牢记一个原则:在启动类对继承basemapper的类进行扫描,谁继承basemapper类就对它进行扫描
package cn.byuan.dao; import cn.byuan.entity.teacher; import com.baomidou.mybatisplus.core.mapper.basemapper; import org.springframework.stereotype.repository; @repository public interface teacherdao extends basemapper<teacher> { }
7.创建service接口及实现类
接口:
import cn.byuan.entity.teacher; import java.util.list; public interface teacherservice { // 添加一位老师 integer addoneteacher(teacher teacher); // 根据id删除一位老师 integer deleteoneteacherbyteacherid(integer teacherid); // 修改一位老师的信息 integer updateoneteacher(teacher teacher); // 根据id查询一位老师 teacher getoneteacherbyteacherid(integer teacherid); // 获取所有老师 list<teacher> getallteacher(); }
实现类:
package cn.byuan.service; import cn.byuan.dao.teacherdao; import cn.byuan.entity.teacher; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import java.util.list; @service public class teacherserviceimp implements teacherservice{ @autowired private teacherdao teacherdao; // 添加一位老师 public integer addoneteacher(teacher teacher){ return teacherdao.insert(teacher); } // 根据id删除一位老师 public integer deleteoneteacherbyteacherid(integer teacherid){ return teacherdao.deletebyid(teacherid); } // 修改一位老师的信息 public integer updateoneteacher(teacher teacher){ return teacherdao.updatebyid(teacher); } // 根据id查询一位老师 public teacher getoneteacherbyteacherid(integer teacherid){ return teacherdao.selectbyid(teacherid); } // 获取所有老师 public list<teacher> getallteacher(){ return teacherdao.selectlist(null); } }
8.在启动类对继承basemapper的类配置扫描
谁继承了basemapper就对谁进行扫描,因为之前我省去了mapper层,直接让dao层接口继承basemapper,因此这里扫描的是dao包
package cn.byuan; import org.mybatis.spring.annotation.mapperscan; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; @springbootapplication @mapperscan("cn.byuan.dao")// 那一层继承了basemapper就对那一层进行扫描 public class test005springbootmybatisplusapplication { public static void main(string[] args) { springapplication.run(test005springbootmybatisplusapplication.class, args); } }
9.在测试类进行测试
package cn.byuan; import cn.byuan.entity.teacher; import cn.byuan.service.teacherservice; import org.junit.jupiter.api.test; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; @springboottest class teacherdaoonetests { @autowired private teacherservice teacherservice; @test void addoneteachertest(){ teacher teacher = new teacher() .setteachername("test2") .setteachersex("女") .setteachersalary(9876.5); teacherservice.addoneteacher(teacher); } @test void deleteoneteacherbyteacheridtest(){ teacherservice.deleteoneteacherbyteacherid(2); } @test void updateoneteacher(){ teacher teacher = new teacher() .setteacherid(1) .setteachername("qwe12") .setteachersex("女") .setteachersalary(1234.5); teacherservice.updateoneteacher(teacher); } @test void getoneteacherbyteacherid(){ teacherservice.getoneteacherbyteacherid(1); } @test void getallteacher(){ teacherservice.getallteacher(); } }
测试结果:
二、实现自动填充功能
自动填充功能一般可以用作记录操作发生时间,如某列的最后修改时间等,本部分代码基于第一部分:
1.修改数据库中的表结构
-- 修改数据库中表结构 alter table tab_teacher add create_time timestamp comment '记录插入时间'; alter table tab_teacher add update_time timestamp comment '记录修改时间'; -- 更新所有表中数据 update tab_teacher set create_time=now(); update tab_teacher set update_time=now(); select * from tab_teacher;
2.修改实体类
这一步简单来说就是将增加的两列添加进teacher类的属性中,其余与第一部分保持一致;
为实现自动填充还应在新加入的两个属性的tablefield中增加"fill"属性
package cn.byuan.entity; import com.baomidou.mybatisplus.annotation.idtype; import com.baomidou.mybatisplus.annotation.tablefield; import com.baomidou.mybatisplus.annotation.tableid; import com.baomidou.mybatisplus.annotation.tablename; import lombok.allargsconstructor; import lombok.data; import lombok.noargsconstructor; import lombok.experimental.accessors; import java.io.serializable; import java.util.date; @noargsconstructor// 创建无参的构造方法 @allargsconstructor// 创建满参的构造方法 @accessors(chain = true)// 使用链式方法 @data// 重写tostring方法等方法 @tablename("tab_teacher")// 对应表名 public class teacher implements serializable { @tableid(value = "pk_teacher_id", type = idtype.auto)// 主键必须有tableid注解 private integer teacherid; @tablefield("teacher_name") private string teachername; @tablefield("teacher_sex") private string teachersex; @tablefield("teacher_salary") private double teachersalary; // 增加的两列属性 @tablefield(value = "create_time", fill = fieldfill.insert)// 插入时自动填充 private date createtime; @tablefield(value = "update_time", fill = fieldfill.insert_update)// 插入和修改时自动填充 private date updatetime; }
3.创建handler层,实现metaobjecthandler接口,重写insertfill与updatefill方法,指定填充的字段及属性值
package cn.byuan.handler; import com.baomidou.mybatisplus.core.handlers.metaobjecthandler; import org.apache.ibatis.reflection.metaobject; import org.springframework.stereotype.component; import java.util.date; @component public class teacherhandler implements metaobjecthandler { @override public void insertfill(metaobject metaobject) { this.strictinsertfill(metaobject, "createtime", date.class, new date()); this.strictinsertfill(metaobject, "updatetime", date.class, new date()); } @override public void updatefill(metaobject metaobject) { this.strictupdatefill(metaobject, "updatetime", date.class, new date()); } }
4.进行测试
这里我们只测试增加和修改两个方法
package cn.byuan; import cn.byuan.entity.teacher; import cn.byuan.service.teacherservice; import org.junit.jupiter.api.test; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; @springboottest class teacherdaotwotests { @autowired private teacherservice teacherservice; @test void addoneteachertest(){ teacher teacher = new teacher() .setteachername("test2") .setteachersex("女") .setteachersalary(9876.5); teacherservice.addoneteacher(teacher); } @test void updateoneteacher(){ teacher teacher = new teacher() .setteacherid(1) .setteachername("wer23") .setteachersex("女") .setteachersalary(1234.5); teacherservice.updateoneteacher(teacher); } }
从sql语句可以看出,在执行update方法时,已自动为我们填充字段
数据库中新插入数据也没有问题
三、实现逻辑删除功能
数据是无价的,因此一般而言我们不会直接删除数据。对于"删除"我们一般的做法是定义一个字段来记录本行数据的可见性
1.修改数据库中的表结构
添加一个字段作为标记
-- 修改数据库中表结构, 添加一个字段作为标记 alter table tab_teacher add visibility tinyint comment "0表示未删除,1表示删除"; -- 更新表中所有数据, 全部设置为未删除 update tab_teacher set visibility=0;
2.在实体类中添加字段,并添加tablefield和tablelogic两个注解
package cn.byuan.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.allargsconstructor; import lombok.data; import lombok.noargsconstructor; import lombok.experimental.accessors; import java.io.serializable; import java.util.date; @noargsconstructor// 创建无参的构造方法 @allargsconstructor// 创建满参的构造方法 @accessors(chain = true)// 使用链式方法 @data// 重写tostring方法等方法 @tablename("tab_teacher")// 对应表名 public class teacher implements serializable { @tableid(value = "pk_teacher_id", type = idtype.auto)// 主键必须有tableid注解 private integer teacherid; @tablefield("teacher_name") private string teachername; @tablefield("teacher_sex") private string teachersex; @tablefield("teacher_salary") private double teachersalary; @tablefield(value = "create_time", fill = fieldfill.insert)// 插入时自动填充 private date createtime; @tablefield(value = "update_time", fill = fieldfill.insert_update)// 插入和修改时自动填充 private date updatetime; // 新添加进来的字段 @tablefield(value = "visibility", fill = fieldfill.insert) @tablelogic(value = "0", delval = "1")// 指定次字段为逻辑删除字段, 默认0是未删除, 1是已删除 private integer visibility; }
3.在teacherhandler中指定visibility字段的初始值
package cn.byuan.handler; import com.baomidou.mybatisplus.core.handlers.metaobjecthandler; import org.apache.ibatis.reflection.metaobject; import org.springframework.stereotype.component; import java.util.date; @component public class teacherhandler implements metaobjecthandler { @override public void insertfill(metaobject metaobject) { this.strictinsertfill(metaobject, "createtime", date.class, new date()); this.strictinsertfill(metaobject, "updatetime", date.class, new date()); // 新添加的字段 this.strictinsertfill(metaobject, "visibility", integer.class, 0); } @override public void updatefill(metaobject metaobject) { this.strictupdatefill(metaobject, "updatetime", date.class, new date()); } }
4.进行测试
这里只测试两个方法,一个是删除指定id值的老师,一个是根据被删除的老师id查询该老师是否可以被查询
package cn.byuan; import cn.byuan.entity.teacher; import cn.byuan.service.teacherservice; import org.junit.jupiter.api.test; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; @springboottest class teacherdaothreetests { @autowired private teacherservice teacherservice; @test void deleteoneteacherbyteacheridtest(){ // 删除id为1的老师 teacherservice.deleteoneteacherbyteacherid(1); } @test void getoneteacherbyteacherid(){ // 查询id为1的老师 teacherservice.getoneteacherbyteacherid(1); } }
可以看到,当我们执行delete方法时,实际上执行的是update方法
而查询语句并没有查询到该老师
数据库中id为1的老师信息依然存在
四、实现分页功能
1.创建一个配置类,通过方法返回一个paginationinterceptor
package cn.byuan.conf; import com.baomidou.mybatisplus.extension.plugins.paginationinterceptor; import org.mybatis.spring.annotation.mapperscan; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; @configuration @mapperscan("cn.byuan.dao") public class pageconfig { @bean public paginationinterceptor paginationinterceptor(){ return new paginationinterceptor(); } }
2.在service中根据selectpage方法进行分页
这里展示两种分页方式,对表中所有数据进行分页以及根据条件进行分页
接口:
package cn.byuan.service; import cn.byuan.entity.teacher; import com.baomidou.mybatisplus.extension.plugins.pagination.page; import java.util.list; public interface teacherservice { // 添加一位老师 integer addoneteacher(teacher teacher); // 根据id删除一位老师 integer deleteoneteacherbyteacherid(integer teacherid); // 修改一位老师的信息 integer updateoneteacher(teacher teacher); // 根据id查询一位老师 teacher getoneteacherbyteacherid(integer teacherid); // 获取所有老师 list<teacher> getallteacher(); // 该部分增加的方法 // 对表中所有信息进行分页, 传入参数为要查询的页数 page<teacher> getallteacherpage(integer pagenumber); // 按条件(性别)进行分页 page<teacher> getallteacherbyteachersexpage(integer pagenumber, string teachersex); }
实现类:
package cn.byuan.service; import cn.byuan.dao.teacherdao; import cn.byuan.entity.teacher; import com.baomidou.mybatisplus.core.conditions.query.querywrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.page; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import java.util.list; @service public class teacherserviceimp implements teacherservice{ @autowired private teacherdao teacherdao; // 添加一位老师 public integer addoneteacher(teacher teacher){ return teacherdao.insert(teacher); } // 根据id删除一位老师 public integer deleteoneteacherbyteacherid(integer teacherid){ return teacherdao.deletebyid(teacherid); } // 修改一位老师的信息 public integer updateoneteacher(teacher teacher){ return teacherdao.updatebyid(teacher); } // 根据id查询一位老师 public teacher getoneteacherbyteacherid(integer teacherid){ return teacherdao.selectbyid(teacherid); } // 获取所有老师 public list<teacher> getallteacher(){ return teacherdao.selectlist(null); } // 该部分增加的方法 // 对表中所有信息进行分页, 传入参数为要查询的页数 public page<teacher> getallteacherpage(integer pagenumber){ querywrapper<teacher> teacherquerywrapper = new querywrapper<>(); page<teacher> teacherpage = new page<>(pagenumber, 5);// 每页大小为5 teacherdao.selectpage(teacherpage, teacherquerywrapper); return teacherpage; } // 按条件(性别)进行分页 public page<teacher> getallteacherbyteachersexpage(integer pagenumber, string teachersex){ querywrapper<teacher> teacherquerywrapper = new querywrapper<>(); teacherquerywrapper.eq("teacher_sex", teachersex);// 根据条件进行分页, 这里填写的是表中的列名 page<teacher> teacherpage = new page<>(pagenumber, 5); teacherdao.selectpage(teacherpage, teacherquerywrapper); return teacherpage; } }
3.进行测试
package cn.byuan; import cn.byuan.entity.teacher; import cn.byuan.service.teacherservice; import com.baomidou.mybatisplus.extension.plugins.pagination.page; import org.junit.jupiter.api.test; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; @springboottest class teacherdaofourtests { @autowired private teacherservice teacherservice; @test void getallteacherpagetest(){ // 查看第三页 page<teacher> teacherpage = teacherservice.getallteacherpage(3); teacherpage.getrecords().foreach(system.out::println); } @test void getallteacherbyteachersexpagetest(){ // 查询男生第1页的内容 page<teacher> teacherpage = teacherservice.getallteacherbyteachersexpage(1, "男"); teacherpage.getrecords().foreach(system.out::println); } }
测试结果
附:page对象的一些常用方法
page<object> page = new page<>(1, 6);// 指定当前页, 每页记录数 page.getcurrent();// 获取当前页 page.gettotal();// 获取总记录数 page.getsize();// 获取每页的记录数 page.getrecords();// 获取当前页数据的集合 page.getpages();// 获取总页数 page.hasnext();// 是否存在下一页 page.hasprevious();// 是否存在上一页
源码地址:
上一篇: 反派死于话多
下一篇: hive学习笔记之八:Sqoop
推荐阅读
-
SpringBoot整合Elasticsearch7.2.0的实现方法
-
SpringBoot整合UEditor的示例代码
-
完整SpringBoot Cache整合redis缓存(二)
-
详解mall整合SpringBoot+MyBatis搭建基本骨架
-
SpringBoot整合Redis、ApachSolr和SpringSession的示例
-
前端笔记知识点整合之HTML5&CSS3(上)新特性&音频视频&本地存储
-
SpringBoot 整合Redis 数据库的方法
-
springboot整合Quartz定时任务
-
SpringBoot整合MyBatisPlus配置动态数据源的方法
-
Springboot整合Urule的方法步骤