MyBatisPlus
快速入门
地址:快速开始 | MyBatis-Plus (baomidou.com)
步骤:
-
创建数据库mybatis_plus
-
创建user表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
id BIGINT NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
DELETE FROM `user`;
INSERT INTO `user` (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
- 编写项目,初始化项目,使用springboot初始化
- 导入依赖、数据库连接配置
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
注:mybatis-plus可以节省我们大量的代码,尽量不用同时导入mybatis和mybatis-plus会有版本差异
spring.datasource.username=root
spring.datasource.password=lhk,1230
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
-
传统方式:pojo-dao(连接mybatis,配置mapper.xml文件)-service-controller
-
使用mybatis-plus之后
- pojo
@Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }
- mapper接口
//在对应的Mapper上面继承基本的类BaseMapper @Repository//代表持久层 public interface UserMapper extends BaseMapper<User> { // 所有的CRUD操作都已经编写了 }
注意:我们需要再主启动类上扫面我们的mapper包下的所有接口
//扫描我们的mapper文件夹 @MapperScan("com.kuang.mapper") @SpringBootApplication public class MybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(MybatisPlusApplication.class, args); } }
- 使用
测试类中测试
@SpringBootTest
class MybatisPlusApplicationTests {
// 继承了BaseMapper,所有方法都来自自己的父类,我们也可以编写自己的扩展方法
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
// 参数Wapper,条件构造器
// 查询全部用户
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
配置日志
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
CRUD扩展
插入操作
Insert插入
@Test
public void testInsert(){
User user = new User();
user.setName("lhk");
user.setAge(3);
user.setEmail("2460445336@qq.com");
int result = userMapper.insert(user);//帮我们自动生成id
System.out.println(result);//受影响的行数
System.out.println(user);//发现,id会自动回填
}
主键生成策略
默认ID_WORKER全局唯一id
分布式系统唯一id生成:
雪花算法:
主键自增
我们需要配置主键自增:
- 实体类字段上==@TableId(type = IdType.AUTO)==
@TableId(type = IdType.AUTO)
private Long id;
- 数据库字段一定是要自增的
其余源码解释
public enum IdType {
AUTO(0),//数据库id自增
NONE(1),//未设置主键
INPUT(2),//手动输入
ID_WORKER(3),//默认的全局唯一id
UUID(4),//全局唯一id uuid
ID_WORKER_STR(5);//ID_WORKER 字符串表示法
}
更新操作
@Test
public void testUpdate(){
User user = new User();
//通过条件自动拼接动态sql
user.setId(2L);
user.setName("hhhhh");
//注意:updataById的参数是一个对象
int i = userMapper.updateById(user);
System.out.println(i);
}
自动填充
创建时间、修改时间这些操作都是自动化完成的
方式一:数据库级别(不建议使用
- 在表中新增字段create_time,update_time
- 再次测试,需要把实体类同步
方式二:代码级别
- 删除数据库的默认值,更新操作
- 实体类字段属性上需要增加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
- 编写处理器来处理这个注解即可
@Slf4j
@Component//不要忘记把处理器加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill.....");
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
乐观锁
乐观锁:它总认为不会出现问题,无论干什么都不上锁,如果出现问题,再次更新值测试
悲观锁:它总认为会出现问题,无论干什么都上锁,再去操作
乐观锁的实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时,set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
乐观锁:1.先查询,获得版本号version=1
--A
updata user set name = "lhk",version = version + 1
where id = 2 and version = 1
--B线程抢先完成,这个时候version=2,会导致A修改失败
updata user set name = "lhk",version = version + 1
where id = 2 and version = 1
测试MP的乐观锁插件
- 给数据库增加version字段
- 我们实体类加对应的字段
@Version//乐观锁version注解
private Integer version;
-
注册组件
//扫描我们的mapper文件夹 @MapperScan("com.kuang.mapper") @EnableTransactionManagement @Configuration//配置类 public class MyBatisPlusConfig { //注册乐观锁插件 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } }
4.测试
// 测试乐观锁成功 @Test public void testOptimisticLocker1(){ // 查询用户信息 User user = userMapper.selectById(2L); // 修改用户信息 user.setName("lhkhhhh"); user.setEmail("234"); // 执行更新操作 userMapper.updateById(user); } // 测试乐观锁失败 @Test public void testOptimisticLocker2(){ // 线程1 User user = userMapper.selectById(2L); user.setName("lhkhhhh"); user.setEmail("234"); // 模拟另一个线程执行插队操作 User user2 = userMapper.selectById(2L); user2.setName("lhkwwww"); user2.setEmail("234"); userMapper.updateById(user2);//强行更新了 userMapper.updateById(user);//如果没有乐观锁就会覆盖插队线程的值 }
查询操作
@Test
public void test1(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 批量查询
@Test
public void test2(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 条件查询之一使用map
@Test
public void test3(){
HashMap<String , Object> map = new HashMap<>();
// 自定义查询
map.put("name","Tom");
List<User> users = userMapper.selectByMap(map);
userMapper.selectByMap(map);
}
分页查询
- 原始的limit进行分页
- pageHelper第三方插件
- MP其实也内置了分页插件
如果使用
- 配置拦截器组件 (在MyBatisPlusConfig类中添加)
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
- 直接使用Page对象即可
//分页查询
@Test
public void testPage(){
//参数一:当前页,参数二:页面大小
Page<User> page = new Page<>(1, 5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
删除操作
基本删除
//测试删除
@Test
public void test4(){
userMapper.deleteById(1L);
}
//通过id批量删除
@Test
public void test5(){
userMapper.deleteBatchIds(Arrays.asList(1L,2L));
}
//通过map删除
public void test6(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","Tom");
userMapper.deleteByMap(map);
}
逻辑删除
物理删除:从数据库中直接移除
逻辑删除:在数据库中没有被移除,是通过一个变量来让他失效
管理员可以查看被删除的记录,防止数据的丢失,类似于回收站
步骤
-
在数据表中增加一个deleted字段
-
我们实体类加对应的字段
@TableLogic//逻辑删除
private Integer deleted;
- 配置
//逻辑删除组件
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
- 测试
最后返回以下信息(走的是更新不是删除)
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6076c66] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1640529691 wrapping com.mysql.cj.jdbc.ConnectionImpl@1857fe6c] will not be managed by Spring
==> Preparing: UPDATE user SET deleted=1 WHERE id=? AND deleted=0
> Parameters: 1(Long)
< Updates: 1
数据库中的数据也没有被删除只是deleted从0变成了1
条件构造器Wrapper
我们写一些复杂的sql就可以使用它替代
测试一:
@Test
void contextLoads() {
//查询name、邮箱不为空的用户,年龄大于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println);
}
测试二
@Test
void test1(){
// 查询名字是tom的人
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","Tom");
User user = userMapper.selectOne(wrapper);//查询一个数据,初见国歌结果使用List或者Map
System.out.println(user);
}
测试三
@Test
void test2(){
//查询年龄在20-30岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30);
Integer count = userMapper.selectCount(wrapper);//查询结果数
System.out.println(count);
}
测试四(模糊查询)
@Test
void test3(){
//名字没有e,email以t开头的
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
代码生成器
package com.wms.common;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输⼊" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输⼊正确的" + tip + "!");
}
/**
* 操作步骤:
* 1.修改数据源包括地址密码信息,对应代码标记:⼀、 下同
* 2.模块配置,可以修改包名
* 3.修改模板(这步可忽略)
* @param args
*/
public static void main(String[] args) {
// 代码⽣成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir")+"/wms";
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("wms");
gc.setOpen(false);
gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//去掉service接⼝⾸字⺟的I, 如DO为User则叫UserService
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
// ⼀、修改数据源
dsc.setUrl("jdbc:mysql://localhost:3306/wms?useUnicode=true&characterEncoding=UTF8&useSSL=false");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("lhk,1230");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
// ⼆、模块配置
pc.setParent("com.wms")
.setEntity("entity")
.setMapper("mapper")
.setService("service")
.setServiceImpl("service.impl")
.setController("controller");
mpg.setPackageInfo(pc);
// ⾃定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// ⾃定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// ⾃定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// ⾃定义输出⽂件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发⽣变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" +
StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType,
String filePath) {
// 判断⾃定义⽂件夹是否需要创建
checkDir("调⽤默认⽅法创建的⽬录,⾃定义⽬录⽤");
if (fileType == FileType.MAPPER) {
// 已经⽣成 mapper ⽂件判断存在,不想重新⽣成返回 false
return !new File(filePath).exists();
}
// 允许⽣成模板⽂件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置⾃定义输出模板
//指定⾃定义模板路径,注意不要带上.ftl/.vm, 会根据使⽤的模板引擎⾃动识别
// 三、修改模板
/*templateConfig.setEntity("templates/entity2.java");
templateConfig.setService("templates/service2.java");
templateConfig.setController("templates/controller2.java");
templateConfig.setMapper("templates/mapper2.java");
templateConfig.setServiceImpl("templates/serviceimpl2.java");*/
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你⾃⼰的⽗类实体,没有就不⽤设置!");
//strategy.setSuperEntityClass("BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共⽗类
//strategy.setSuperControllerClass("BaseController");
// strategy.setSuperControllerClass("你⾃⼰的⽗类控制器,没有就不⽤设置!");
// 写于⽗类中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英⽂逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//strategy.setTablePrefix(pc.getModuleName() + "_");
// 忽略表前缀tb_,⽐如说tb_user,直接映射成user对象
// 四、注意是否要去掉表前缀
//strategy.setTablePrefix("tb_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
(true);
// 公共⽗类
//strategy.setSuperControllerClass(“BaseController”);
// strategy.setSuperControllerClass(“你⾃⼰的⽗类控制器,没有就不⽤设置!”);
// 写于⽗类中的公共字段
// strategy.setSuperEntityColumns(“id”);
strategy.setInclude(scanner(“表名,多个英⽂逗号分割”).split(“,”));
strategy.setControllerMappingHyphenStyle(true);
//strategy.setTablePrefix(pc.getModuleName() + "");
// 忽略表前缀tb,⽐如说tb_user,直接映射成user对象
// 四、注意是否要去掉表前缀
//strategy.setTablePrefix(“tb_”);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}