MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
maven依赖
com.baomidou mybatis-plus-boot-starter-test 3.5.2
数据库
DROP TABLE IF EXISTS user;CREATE TABLE user
(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) 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');
配置application.properties文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.name=defaultDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
编写pojo类User
package com.rui.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private Long id;private String name;private Integer age;private String email;
}
编写mapper类
package com.rui.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rui.pojo.User;
import org.springframework.stereotype.Repository;//在对应的Mapper上面实现基本的类BaseMapper
@Repository
public interface UserMapper extends BaseMapper {//所有的CRUD已经编写完成
}
在springboot启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:
@MapperScan("com.rui.mapper")
启动测试!
@Test
void test1() {User user = new User();user.setName("叶辰");user.setAge(18);user.setEmail("206875469@qq.com");System.out.println(userMapper.insert(user));
}
主键生成策略
默认 ID_WORKER 全局唯一id
分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html
雪花算法: snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为 毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味 着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯 一!
设置主键自增:在数据库表中设置id自动递增,在User类中id属性上面添加@TableId(type = IdType.AUTO
其与的源码解释
public enum IdType {AUTO(0), // 数据库id自增NONE(1), // 未设置主键INPUT(2), // 手动输入ID_WORKER(3), // 默认的全局唯一idUUID(4), // 全局唯一id uuidID_WORKER_STR(5); //ID_WORKER 字符串表示法
}
使用updateById()参数是泛型T
@Test
void test2() {User user = new User();user.setId(3L);user.setName("叶辰");System.out.println(userMapper.updateById(user));
}
所有的sql都是帮你自动动态的配置的!
自动填充
添加字段
//字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
创建MyMetaObjectHandler实现MetaObjectHandler接口
package com.rui.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;import java.util.Date;@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("插入自动填充开始...");//default MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {log.info("更新自动填充开始...");this.setFieldValByName("updateTime",new Date(),metaObject);}
}
测试
乐观锁、悲观锁
乐观锁 : 故名思意十分乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出现了问题, 再次更新值测试
悲观锁:故名思意十分悲观,它总是认为总是出现问题,无论干什么都会上锁!再去操作!
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
-- 乐观锁:1、先查询,获得版本号 version = 1-- A
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1-- B 线程抢先完成,这个时候 version = 2,会导致 A 修改失败!
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
乐观锁插件
数据库和实体类添加int version
@Version
private Integer version;
创建MyBatisPlusConfig配置类
package com.rui.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;@MapperScan("com.rui.mapper")
@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {//注册乐观锁插件//旧版// @Bean// public OptimisticLockerInterceptor optimisticLockerInterceptor() {// return new OptimisticLockerInterceptor();// }//新版@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return mybatisPlusInterceptor;}}
测试
//测试乐观锁成功
@Test
void test3() {User user = userMapper.selectById(1L);user.setName("root");user.setEmail("root");userMapper.updateById(user);
}
//测试乐观锁失败
@Test
void test4() {//线程1User user = userMapper.selectById(1L);user.setName("root111");user.setEmail("root111");//线程2:模拟插队操作User user2 = userMapper.selectById(1L);user2.setName("root222");user2.setEmail("root222");userMapper.updateById(user2);//自旋锁来多次尝试提交userMapper.updateById(user);//如果没有乐观锁数据库中就会覆盖插队线程2的值!
}
@Test
void test5() {//单个查询System.out.println("单个查询------");System.out.println(userMapper.selectById(1));//批量查询System.out.println("批量查询------");for (User selectBatchId : userMapper.selectBatchIds(Arrays.asList(1, 2, 3))) {System.out.println(selectBatchId);}//条件查询mapSystem.out.println("条件查询map------");HashMap map = new HashMap<>();map.put("name","叶辰");System.out.println(userMapper.selectByMap(map));//全部查询System.out.println("全部查询------");//参数是一个wapper,条件构造器for (User user : userMapper.selectList(null)) {System.out.println(user);}
}
分页查询
修改MyBatisPlusConfig类
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();//乐观锁插件mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//分页插件mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//也可以不传DbType.MYSQL,为空时会通过URL判断数据库类型// if (url.contains(":mysql:") || url.contains(":cobar:")) {// return DbType.MYSQL;return mybatisPlusInterceptor;
}
测试
@Test
void test6() {Page page = new Page<>(2, 5);userMapper.selectPage(page,null);page.getRecords().forEach(System.out::println);
}
与select类似
@Test
void test7() {userMapper.deleteById(1582728670388129794L);userMapper.deleteBatchIds(Arrays.asList(1,2,3));HashMap map = new HashMap<>();map.put("name","叶辰");userMapper.deleteByMap(map);
}
逻辑删除
物理删除 :从数据库中直接移除
逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1
管理员可以查看删除的记录!防止数据的丢失!
在数据表和实体类中添加deleted字段
@TableLogic //逻辑删除
private Integer deleted;
高版本已经不用再去配置MyBatisPlusConfig插入组件
只需要注解+application.properties配置即可
#逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
查询会自动加上delete字段,除了管理员之外无法查询
导入依赖
p6spy p6spy 3.9.1
修改driver-class-name url application.properties文件
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.name=defaultDataSource
spring.datasource.url= jdbc:p6spy:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spy.properties文件
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
测试使用!上线会影响性能
set、setSql、lambda
测试等等
package com.rui.mybatis_plus;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rui.mapper.UserMapper;
import com.rui.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class WrapperTest {//继承了BaseMapper,所有的方法都来自自己的父类@Autowiredprivate UserMapper userMapper;@Testvoid test1(){//查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于20QueryWrapper wrapper = new QueryWrapper<>();wrapper.isNotNull("name").isNotNull("email").ge("age",20);userMapper.selectList(wrapper).forEach(System.out::println);}@Testvoid test2(){//查询指定nameQueryWrapper wrapper = new QueryWrapper<>();wrapper.eq("name","叶辰");userMapper.selectList(wrapper).forEach(System.out::println);}@Testvoid test3(){//查询指定nameQueryWrapper wrapper = new QueryWrapper<>();wrapper.between("age",12,20);userMapper.selectList(wrapper).forEach(System.out::println);System.out.println("数量为:"+userMapper.selectCount(wrapper));}@Testvoid test4(){//模糊查询QueryWrapper wrapper = new QueryWrapper<>();wrapper.notLike("name","叶").likeRight("email","t");userMapper.selectList(wrapper).forEach(System.out::println);}@Testvoid test5(){//模糊查询QueryWrapper wrapper = new QueryWrapper<>();wrapper.inSql("id","select id from user where id<5");userMapper.selectList(wrapper).forEach(System.out::println);}}
3.5.1以下的版本:
dao、pojo、service、controller都给我自己去编写完成!
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、 Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
package com.kuang;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
// 代码自动生成器
public class KuangCode {public static void main(String[] args) {// 需要构建一个 代码自动生成器 对象AutoGenerator mpg = new AutoGenerator();// 配置策略// 1、全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath+"/src/main/java");gc.setAuthor("狂神说");gc.setOpen(false);gc.setFileOverride(false); // 是否覆盖gc.setServiceName("%sService"); // 去Service的I前缀gc.setIdType(IdType.ID_WORKER);gc.setDateType(DateType.ONLY_DATE);gc.setSwagger2(true);mpg.setGlobalConfig(gc);//2、设置数据源DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/kuang_community?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");dsc.setDbType(DbType.MYSQL);mpg.setDataSource(dsc);//3、包的配置PackageConfig pc = new PackageConfig();pc.setModuleName("blog");pc.setParent("com.kuang");pc.setEntity("entity");pc.setMapper("mapper");pc.setService("service");pc.setController("controller");mpg.setPackageInfo(pc);//4、策略配置StrategyConfig strategy = new StrategyConfig();strategy.setInclude("blog_tags","course","links","sys_settings","user_record","user_say"); // 设置要映射的表名strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);strategy.setEntityLombokModel(true); // 自动lombok;strategy.setLogicDeleteFieldName("deleted");// 自动填充配置TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);TableFill gmtModified = new TableFill("gmt_modified",FieldFill.INSERT_UPDATE);ArrayList tableFills = new ArrayList<>();tableFills.add(gmtCreate);tableFills.add(gmtModified);strategy.setTableFillList(tableFills);// 乐观锁strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2mpg.setStrategy(strategy);mpg.execute(); //执行}
}
测试生成
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rx4dGf0S-1666696695905)(D:\program files\TyporaImg\image-20221021155036126.png)]
3.5.1以上的版本:`
com.baomidou mybatis-plus-generator 最新版本
快速生成
FastAutoGenerator.create("url", "username", "password").globalConfig(builder -> {builder.author("baomidou") // 设置作者.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件.outputDir("D://"); // 指定输出目录}).packageConfig(builder -> {builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名.moduleName("system") // 设置父包模块名.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径}).strategyConfig(builder -> {builder.addInclude("t_simple") // 设置需要生成的表名.addTablePrefix("t_", "c_"); // 设置过滤表前缀}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板.execute();
交互式生成
FastAutoGenerator.create(DATA_SOURCE_CONFIG)// 全局配置.globalConfig((scanner, builder) -> builder.author(scanner.apply("请输入作者名称?")).fileOverride())// 包配置.packageConfig((scanner, builder) -> builder.parent(scanner.apply("请输入包名?")))// 策略配置.strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all"))).controllerBuilder().enableRestStyle().enableHyphenStyle().entityBuilder().enableLombok().addTableFills(new Column("create_time", FieldFill.INSERT)).build())/*模板引擎配置,默认 Velocity 可选模板引擎 Beetl 或 Freemarker.templateEngine(new BeetlTemplateEngine()).templateEngine(new FreemarkerTemplateEngine())*/.execute();// 处理 all 情况
protected static List getTables(String tables) {return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
样例
…
上一篇:剑南春|米兰2-1客胜佛罗伦萨迎6连胜,莱奥传射,奇克建功 剑南春|米兰2-1客胜佛罗伦萨迎6连胜,莱奥传射,奇克建功
下一篇:C罗上演帽子戏法!218天后再次戴帽 破38天运动战球荒刷8纪录 C罗上演帽子戏法!218天后再次戴帽 破38天运动战球荒刷8纪录