①:创建新模块,选择Spring初始化,并配置模块相关基础信息
③:手动添加MyBatisPlus起步依赖
<dependency> <groupId>com.baomidougroupId> <artifactId>mybatis-plus-boot-starterartifactId> <version>3.4.1version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>1.1.16version> dependency> <dependency> <groupId>org.projectlombokgroupId> <artifactId>lombokartifactId> <version>1.18.26version> dependency>
- 注意事项1:由于mp并未被收录到idea的系统内置配置,无法直接选择加入
- 注意事项2:如果使用Druid数据源,需要导入对应坐标
④:制作实体类与表结构(类名与表名对应,属性名与字段名对应)
create database if not exists mybatisplus_db character set utf8; use mybatisplus_db; CREATE TABLE user ( id bigint(20) primary key auto_increment, name varchar(32) not null, password varchar(32) not null, age int(3) not null , tel varchar(32) not null ); insert into user values(null,'tom','123456',12,'12345678910'); insert into user values(null,'jack','123456',8,'12345678910'); insert into user values(null,'jerry','123456',15,'12345678910'); insert into user values(null,'tom','123456',9,'12345678910'); insert into user values(null,'snake','123456',28,'12345678910'); insert into user values(null,'张益达','123456',22,'12345678910'); insert into user values(null,'张大炮','123456',16,'12345678910');
@Data @NoArgsConstructor @AllArgsConstructor public class User { private Long id; private String name; private String password; private Integer age; private String tel; }
⑤:设置Jdbc参数(application.yml)
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource #指定数据源类型为druid,springboot默认为hikari数据源 driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC username: root password: root
⑥:定义数据接口,继承BaseMapper
package com.yishooo.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yishooo.pojo.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<User> { }
⑦:测试类中注入dao接口,测试功能
package com.yishooo.dao; import com.yishooo.pojo.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest public class UserMapperTest { @Autowired private UserMapper userMapper; @Test void testGetAll() { List<User> userList = userMapper.selectList(null); System.out.println(userList); } }
MyBatisPlus(简称MP)是基于MyBatis框架基础上开发的增强型工具,旨在简化开发、提高效率
官网:https/mybatis.plus/ https://mp.baomidou.com/
- 无侵入:只做增强不做改变,不会对现有工程产生影响
- 强大的 CRUD 操作:内置通用 Mapper,少量配置即可实现单表CRUD 操作
- 支持 Lambda:编写查询条件无需担心字段写错
- 支持主键自动生成
- 内置分页插件
- ……
package com.yishooo.dao; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.yishooo.pojo.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest public class CRUDTest { @Autowired private UserMapper userMapper; @Test public void testSave() throws Exception{ User user = new User(); user.setName("隔壁老王"); user.setPassword("laowang"); user.setAge(12); user.setTel("4008208820"); userMapper.insert(user); } @Test void testDelete() { userMapper.deleteById(1666284193435480066L); } @Test void testUpdate() { User user = new User(); user.setId(1L); user.setName("Tom888"); user.setPassword("tom888"); userMapper.updateById(user); } @Test void testGetById() { User user = userMapper.selectById(2L); System.out.println(user); } @Test void testGetAll() { List<User> userList = userMapper.selectList(null); for (User user : userList) { System.out.println(user); } } }
MyBatisPlus分页使用
①:设置分页拦截器作为Spring管理的bean
package com.yishooo.config; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MPConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ //1 创建MybatisPlusInterceptor拦截器对象 MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //2 添加分页拦截器 interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); return interceptor; } }
②:执行分页查询
//分页查询 @Test void testSelectPage(){ //1 创建IPage分页对象,设置分页参数 IPage<User> page=new Page<>(1,3); //2 执行分页查询 userDao.selectPage(page,null); //3 获取分页结果 System.out.println("当前页码值:"+page.getCurrent()); System.out.println("每页显示数:"+page.getSize()); System.out.println("总页数:"+page.getPages()); System.out.println("总条数:"+page.getTotal()); System.out.println("当前页数据:"+page.getRecords()); }
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC username: root password: root # 开启mp的日志(输出到控制台) mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
在resources下新建一个logback.xml文件,名称固定,内容如下:
<configuration> configuration>
关于logback参考博客:https://www.jianshu.com/p/75f9d11ae011
spring: main: banner-mode: off # 关闭SpringBoot启动图标(banner)
# mybatis-plus日志控制台输出 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: banner: off # 关闭mybatisplus启动图标
方式一:按条件查询
//方式一:按条件查询 QueryWrapper<User> qw=new QueryWrapper<>(); qw.lt("age", 18); List<User> userList = userMapper.selectList(qw); System.out.println(userList);
方式二:lambda格式按条件查询
//方式二:lambda格式按条件查询 QueryWrapper<User> qw = new QueryWrapper<User>(); qw.lambda().lt(User::getAge, 10); List<User> userList = userMapper.selectList(qw); System.out.println(userList);
方式三:lambda格式按条件查询(推荐)
//方式三:lambda格式按条件查询 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.lt(User::getAge, 10); List<User> userList = userMapper.selectList(lqw); System.out.println(userList);
并且关系(and)
//并且关系 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //并且关系:10到30岁之间 lqw.lt(User::getAge, 30).gt(User::getAge, 10); List<User> userList = userMapper.selectList(lqw); System.out.println(userList);
或者关系(or)
//或者关系 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //或者关系:小于10岁或者大于30岁 lqw.lt(User::getAge, 10).or().gt(User::getAge, 30); List<User> userList = userMapper.selectList(lqw); System.out.println(userList);
问题导入
if语句控制条件追加
Integer minAge=10; //将来有用户传递进来,此处简化成直接定义变量了 Integer maxAge=null; //将来有用户传递进来,此处简化成直接定义变量了 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); if(minAge!=null){ lqw.gt(User::getAge, minAge); } if(maxAge!=null){ lqw.lt(User::getAge, maxAge); } List<User> userList = userMapper.selectList(lqw); userList.forEach(System.out::println);
条件参数控制
Integer minAge=10; //将来有用户传递进来,此处简化成直接定义变量了 Integer maxAge=null; //将来有用户传递进来,此处简化成直接定义变量了 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //参数1:如果表达式为true,那么查询才使用该条件 lqw.gt(minAge!=null,User::getAge, minAge); lqw.lt(maxAge!=null,User::getAge, maxAge); List<User> userList = userMapper.selectList(lqw); userList.forEach(System.out::println);
条件参数控制(链式编程)
Integer minAge=10; //将来有用户传递进来,此处简化成直接定义变量了 Integer maxAge=null; //将来有用户传递进来,此处简化成直接定义变量了 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //参数1:如果表达式为true,那么查询才使用该条件 lqw.gt(minAge!=null,User::getAge, minAge) .lt(maxAge!=null,User::getAge, maxAge); List<User> userList = userMapper.selectList(lqw); userList.forEach(System.out::println);
/*LambdaQueryWrapper
lqw = new LambdaQueryWrapper //或者 QueryWrapper<User> lqw = new QueryWrapper<User>(); lqw.select("id", "name", "age", "tel"); List<User> userList = userMapper.selectList(lqw); System.out.println(userList);(); lqw.select(User::getId, User::getName, User::getAge);*/
QueryWrapper<User> lqw = new QueryWrapper<User>(); lqw.select("count(*) as count, tel"); lqw.groupBy("tel"); List<Map<String, Object>> userList = userMapper.selectMaps(lqw); System.out.println(userList);
多条件查询有哪些组合?
- 范围匹配(> 、 = 、between)
- 模糊匹配(like)
- 空判定(null)
- 包含性匹配(in)
- 分组(group)
- 排序(order)
- ……
- 用户登录(eq匹配)
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //等同于= lqw.eq(User::getName, "Jerry").eq(User::getPassword, "jerry"); User loginUser = userMapper.selectOne(lqw); System.out.println(loginUser);
- 购物设定价格区间、户籍设定年龄区间(le ge匹配 或 between匹配)
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //范围查询 lt le gt ge eq between lqw.between(User::getAge, 10, 30); List<User> userList = userMapper.selectList(lqw); System.out.println(userList);
- 查信息,搜索新闻(非全文检索版:like匹配)
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //模糊匹配 like %J% 不走索引 效率较低 lqw.likeRight(User::getName, "J");//J% 走索引 List<User> userList = userMapper.selectList(lqw); System.out.println(userList);
- 统计报表(分组查询聚合函数)
QueryWrapper<User> qw = new QueryWrapper<User>(); qw.select("age","count(*) as nums"); qw.groupBy("age"); List<Map<String, Object>> maps = userMapper.selectMaps(qw); System.out.println(maps);
- 更多查询条件设置参看 https://mybatis.plus/guide/wrapper.html#abstractwrapper
思考表的字段和实体类的属性不对应,查询会怎么样?
6.4.4 问题四:表名与编码开发设计不同步
@Data @TableName("tbl_user") public class User { /* id为Long类型,因为数据库中id为bigint类型, 并且mybatis有自己的一套id生成方案,生成出来的id必须是Long类型 */ private Long id; private String name; @TableField(value = "pwd",select = false) private String password; private Integer age; private String tel; @TableField(exist = false) //表示online字段不参与CRUD操作 private Boolean online; }
主键生成的策略有哪几种方式?不同的表应用不同的id生成策略
- 日志:自增(1,2,3,4,……)
- 购物订单:特殊规则(FQ23948AK3843)
- 外卖单:关联地区日期等信息(10 04 20200314 34 91)
- 关系表:可省略id
- ……
mybatis-plus: global-config: db-config: id-type: assign_id #配置全局的id生成为雪花算法 table-prefix: tb_ #配置表的统一的前缀
MyBatisPlus是否支持批量操作?
//删除指定多条数据 List<Long> list = new ArrayList<>(); list.add(1402551342481838081L); list.add(1402553134049501186L); list.add(1402553619611430913L); userMapper.deleteBatchIds(list);
//查询指定多条数据 List<Long> list = new ArrayList<>(); list.add(1L); list.add(3L); list.add(4L); userMapper.selectBatchIds(list);
在实际环境中,如果想删除一条数据,是否会真的从数据库中删除该条数据?
②:实体类中添加对应字段,并设定当前字段为逻辑删除标记字段
package com.yishooo.pojo; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; @Data public class User { private Long id; //逻辑删除字段,标记当前记录是否被删除 @TableLogic private Integer deleted; }
③:配置逻辑删除字面值
mybatis-plus: global-config: db-config: table-prefix: tbl_ # 逻辑删除字段名 logic-delete-field: deleted # 逻辑删除字面值:未删除为0 logic-not-delete-value: 0 # 逻辑删除字面值:删除为1 logic-delete-value: 1
乐观锁主张的思想是什么?
- 业务并发现象带来的问题:秒杀
②:实体类中添加对应字段,并设定当前字段为逻辑删除标记字段
package com.yishooo.pojo; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.Version; import lombok.Data; @Data public class User { private Long id; @Version private Integer version; }
③:配置乐观锁拦截器实现锁机制对应的动态SQL语句拼装
package com.yishooo.config; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MpConfig { @Bean public MybatisPlusInterceptor mpInterceptor() { //1.定义Mp拦截器 MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor(); //2.添加乐观锁拦截器 mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mpInterceptor; } }
④:使用乐观锁机制在修改前必须先获取到对应数据的verion方可正常进行
@Test public void testUpdate() { /*User user = new User(); user.setId(3L); user.setName("Jock666"); user.setVersion(1); userMapper.updateById(user);*/ //1.先通过要修改的数据id将当前数据查询出来 //User user = userMapper.selectById(3L); //2.将要修改的属性逐一设置进去 //user.setName("Jock888"); //userMapper.updateById(user); //1.先通过要修改的数据id将当前数据查询出来 User user = userMapper.selectById(3L); //version=3 User user2 = userMapper.selectById(3L); //version=3 user2.setName("Jock aaa"); userMapper.updateById(user2); //version=>4 user.setName("Jock bbb"); userMapper.updateById(user); //verion=3?条件还成立吗? }
如果只给一张表的字段信息,能够推演出Domain、Dao层的代码?
- Mapper接口模板
- 实体对象类模板
- 第一步:创建SpringBoot工程,添加代码生成器相关依赖,其他依赖自行添加
<dependency> <groupId>com.baomidougroupId> <artifactId>mybatis-plus-generatorartifactId> <version>3.4.1version> dependency> <dependency> <groupId>org.apache.velocitygroupId> <artifactId>velocity-engine-coreartifactId> <version>2.3version> dependency>
- 第二步:编写代码生成器类
package com.yishooo; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; public class Generator { public static void main(String[] args) { //1. 创建代码生成器对象,执行生成代码操作 AutoGenerator autoGenerator = new AutoGenerator(); //2. 数据源相关配置:读取数据库中的信息,根据数据库表结构生成代码 DataSourceConfig dataSource = new DataSourceConfig(); dataSource.setDriverName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC"); dataSource.setUsername("root"); dataSource.setPassword("root"); autoGenerator.setDataSource(dataSource); //3. 执行生成操作 autoGenerator.execute(); } }
- 设置全局配置
//设置全局配置 GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setOutputDir(System.getProperty("user.dir")+"/mybatisplus_04_generator/src/main/java"); //设置代码生成位置 globalConfig.setOpen(false); //设置生成完毕后是否打开生成代码所在的目录 globalConfig.setAuthor("yishooo"); //设置作者 globalConfig.setFileOverride(true); //设置是否覆盖原始生成的文件 globalConfig.setMapperName("%sMapper"); //设置数据层接口名,%s为占位符,指代模块名称 globalConfig.setIdType(IdType.ASSIGN_ID); //设置Id生成策略 autoGenerator.setGlobalConfig(globalConfig);
- 设置包名相关配置
//设置包名相关配置 PackageConfig packageInfo = new PackageConfig(); packageInfo.setParent("com.yishooo"); //设置生成的包名,与代码所在位置不冲突,二者叠加组成完整路径 packageInfo.setEntity("pojo"); //设置实体类包名 packageInfo.setMapper("mapper"); //设置数据层包名 autoGenerator.setPackageInfo(packageInfo);
- 策略设置
//策略设置 StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig.setInclude("tb_user"); //设置当前参与生成的表名,参数为可变参数 strategyConfig.setTablePrefix("tb_"); //设置数据库表的前缀名称,模块名 = 数据库表名 - 前缀名 例如: User = tb_user - tb_ strategyConfig.setRestControllerStyle(true); //设置是否启用Rest风格 strategyConfig.setVersionFieldName("version"); //设置乐观锁字段名 strategyConfig.setLogicDeleteFieldName("deleted"); //设置逻辑删除字段名 strategyConfig.setEntityLombokModel(true); //设置是否启用lombok autoGenerator.setStrategy(strategyConfig);
说明:根据实际情况修改后可以直接使用。