MyBatisPlus

MyBatisPlus

MyBatisPlus可以节省我们大量的时间,简化MyBaits,所有的CRUD代码它都可以自动化完成。

快速入门

使用第三方组件:
1,导入对应的依赖
2,研究依赖如何配置
3,代码如何编写
4,提高扩展能力

步骤
1,创建数据库 mybatis_plus
2, 创建User表

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)
);

  • 真实开发中,version(乐观锁),deleted(逻辑删除),gmt_create,gmt_modified这些字段必须添加。

3.创建项目
4.导入依赖
< !-- 数据库驱动–>
< dependency>
< groupId>mysql< /groupId>
< artifactId>mysql-connector-java< /artifactId>
< /dependency>
< !-- mybatisplus是自己开发的,并非官方的–>
< dependency>
< groupId>com.baomidou< /groupId>
< artifactId>mybatis-plus-boot-starter< /artifactId>
< version>3.4.1< /version>
< /dependency>
导入mybatis-plus依赖后就不用导入mybatis了

说明:我们使用mybatis-plus可以节省我们大量的代码,尽量不要同时导入mybatis和mybatis-plus

5.连接数据库
配置文件
mysql5 驱动不同
spring:
datasource:
username: root
password: 12345
url: jdbc:mysql://localhost:3306/mybatisplus?userSSL=false&userUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver

mysql 8 驱动不同,需要增加时区的配置:com.mysql.cj.jdbc.Driver,时区配置serverTimezone=GMT
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatisplus?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
username: root
password: 12345
driver-class-name: com.mysql.cj.jdbc.Driver

传统方式:
entity-mapper(连接mybatis,配置xml文件)-service-controller
使用了mybatisPlus之后:
entity-mapper接口-使用
mapper类:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hua.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
//在对应的Mapper上面继承基本的接口 BaseMapper,注意补全泛型
public interface UserMapper extends BaseMapper< User> {
//所有的简单的CRUD操作完成
}
然后在主方法添加注解@MapperScan(“com.hua.mapper”)//扫描mapper文件夹
至此,已经可以进行简单查询了。
List< User> users = userMapper.selectList(null);

配置日志

我们所有的sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志。
配制yaml:
#配置日志 这里可以用log4j等,这里是直接控制台输出
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

配置完毕之后就可以看日志了。

CRUD扩展

insert插入
@Test
public void testInsert(){
User user = new User();
user.setName(“lolo”);
user.setAge(19);
user.setEmail(“7918@”);
int result = userMapper.insert(user);//帮我们自动生成id
System.out.println(user);//受影响行数
System.out.println(result);//发现,id会自动回填
}

数据库插入的id默认值为:全局唯一的ID

主键生成策略:
雪花算法:
https://www.cnblogs.com/haoxinyue/p/5208136.html

  • Twitter的snowflake算法(雪花算法)
    snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心:北京,上海,西雅图等,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。具体实现的代码可以参看https://github.com/twitter/snowflake。可以保证几乎全球唯一!

主键自增
我们需要配置主键自增:
1,在实体类上增加:@TableId(type = IdType.AUTO) //表的id
2,数据库字段一定要是自增的
IdType.AUTO//数据库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.setName(“liio”);
user.setAge(20);
user.setEmail(“791813@”);
//注意:updateById参数是一个对象!
int i = userMapper.updateById(user);
System.out.println(i);
}
所有的sql都是自动帮你动态配置的

自动填充
创建时间,修改时间,这些操作一般都是自动化完成的,我们不希望手动更新!

阿里巴巴开发手册:所有的数据库表:gmt:全球时间
gmt_create(创建时间),gmt_modify(修改时间)几乎所有的表都要必备,而且需要自动化
方式一:数据库级别(工作中不允许修改数据库字段
1,在表中新增字段create_time,update_time
在这里插入图片描述
2,再次测试插入方法,记得先把实体类同步。

方式二:代码级别
1,删除数据库的默认值
2,实体类的字段属性上需要增加注解
//字段添加填充内容。
@TableField(fill = FieldFill.INSERT) //表的字段,
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3,新建一个handler包,新建一个MyDataObjHandler 类,编写这个处理器,处理这个注解
@Component//注意此处不要忘记
@Slf4j
public class MyDataObjHandler 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 insert fill---");
    this.setFieldValByName("updateTime",new Date(),metaObject);
}

}

乐观锁
乐观锁:version,new version
实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时,set version = newVsersion where version = oldVersion
  • 如果version不对,就更新失败

update user set name = “kuangshen”,version = version+1 where i =2 and version = 1;

测试一下MP的乐观锁插件
1,给数据库中增加version字段
2,更改实体类字段,并加上注解
@Version //乐观锁的注解
private Integer version;
3,注册组件
新建一个config
@EnableTransactionManagement//自动管理事务
@Configuration//配置类
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
最新版本MybatisPlus只需要添加注解即可
支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整数类型下 newVersion = oldVersion + 1
newVersion 会回写到 entity 中
仅支持 updateById(id) 与 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能复用!!!

查询操作

@Test
public void testSelectById(){
User user = userMapper.selectById(1);
System.out.println(user);
}
//测试批量查询
@Test
public void testSelectByBatchId(){
List users = userMapper.selectBatchIds(Arrays.asList(1,2,3));
users.forEach(System.out::println);
}
//条件查询 map
public void testSlectByBatchIds(){
HashMap<String,Object> map = new HashMap<>();
//自定义查询条件
map.put(“name”,“kuangshen”);
map.put(“age”,3);
List users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}

分页查询
分页在网站使用的十分之多
1.原始 limit
2.第三方插件pageHelper
3.MP其实也内置了分页插件

如何使用
1,配置
//Spring boot方式
@Configuration
@MapperScan(“com.baomidou.cloud.service..mapper”)
public class MybatisPlusConfig {

// 旧版
@Bean
public PaginationInterceptor paginationInterceptor() {
    PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
    // paginationInterceptor.setOverflow(false);
    // 设置最大单页限制数量,默认 500 条,-1 不受限制
    // paginationInterceptor.setLimit(500);
    // 开启 count 的 join 优化,只针对部分 left join
    paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
    return paginationInterceptor;
}

// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
}

}

2,直接使用Page对象即可
@Test
public void testPage(){
//参数1,当前页
//参数2,页面大小
Page< User> objectPage = new Page<>(1,5);//查第一页,每页五个数据
userMapper.selectPage(objectPage,null);
objectPage.getRecords().forEach(System.out::println);
System.out.println(objectPage.getTotal());//获得总页数
}

删除操作

基本的删除操作
1,根据id删除记录
@Test
public void testDeleteById(){
userMapper.deleteById(1);
}
//通过id批量删除
@Test
public void testDeletePBatchById(){
userMapper.deleteBatchIds(Arrays.asList(1,2,3));
}
//通过map批量删除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put(“name”,“狂神”);
userMapper.deleteByMap(map);
}

逻辑删除
物理删除:从数据库中移除。
逻辑删除:在数据库中没有被移除,而是通过变量来让它失效。

1,在数据表中增加一个deleted字段
2,实体类中增加对应代码 ,注意添加注解
@TableLogic //逻辑删除注解
private Integer deleted;

3,配置yaml
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
4,测试
此后删除走的就是更新操作,并不是删除操作
记录依旧在数据库,但是值确实已经变化了。
查询操作的时候会自动过滤被删除的字段

以上所有CRUD操作及其扩展操作,我们都必须精通掌握。

性能分析插件,执行 SQL 分析打印

我们在平时的开发中,会遇到一些慢sql,测试,druid。。。
MP也提供性能分析插件,如果超过这个时间就停止运行!
1,导入插件
2,测试使用

条件构造器Wrapper

我们写一些复杂的sql就可以使用它来替代!
测试1
//继承了BaseMapper,所有的方法都来自父类,也可以编写自己的拓展方法
@Autowired
private UserMapper userMapper;
@Test
void wrapper(){
//查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12.
QueryWrapper< User> wrapper = new QueryWrapper<>();
wrapper.isNotNull(“name”)
.isNotNull(“email”)
.ge(“age”,12); //g大于 e等于
userMapper.selectList(wrapper).forEach(System.out::println);//和我们刚才学习的map对比一下

}

测试2
@Test
void wrapper(){
//查询名字狂神说
QueryWrapper< User> wrapper = new QueryWrapper<>();
wrapper.eq(“name”,“kuangshensshuo”);
User user = userMapper.selectOne(wrapper);//查询一个数据,出现多个结果使用List或者Map
System.out.println(user);
}
测试3
@Test
void wrapper(){
//bewteen and 年龄在20-30岁之间的用户
QueryWrapper< User> wrapper = new QueryWrapper<>();
wrapper.between(“age”,20,30);//区间
Integer count = userMapper.selectCount(wrapper);//查询结果数
System.out.println(count);
}
测试4
@Test
void test(){

    //模糊查询  查询名字中不包含e的
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
            .notLike("name","e")
            .likeRight("email","t") ;          //左和右,百分号的位置  %e%
    List<Map<String ,Object>> maps = userMapper.selectMaps(wrapper);
    maps.forEach(System.out::println);
}

测试5
@Test
void test(){
//模糊查询
QueryWrapper< User> wrapper = new QueryWrapper<>();
//id在子查询中查询出来
//in查询
wrapper.inSql(“id”,“select id from user where id<3”);

    List<Object> objects = userMapper.selectObjs(wrapper);
    objects.forEach(System.out::println);
}

测试6
@Test
void test(){
//排序,通过id
QueryWrapper< User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc(“id”);
List< User> objects = userMapper.selectList(wrapper);
objects.forEach(System.out::println);
}

代码自动生成器

entity,service,controller自动生成
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
参考官方文档

package com.hua;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
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 AutoCode {
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("hua");//作者名字
    gc.setOpen(false);
    gc.setFileOverride(false);//是否覆盖原来的
    gc.setServiceName("%sService");//服务的名字,去Service的i前缀
    gc.setIdType(IdType.AUTO);//id初始算法
    gc.setDateType(DateType.ONLY_DATE);//日期的类型
    gc.setSwagger2(true);
    //丢到自动生成器
    mpg.setGlobalConfig(gc);
    //2,设置数据源
    final DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT");
    dsc.setUsername("root");
    dsc.setPassword("12345");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setDbType(DbType.MYSQL);
    mpg.setDataSource(dsc);

    //3,包的配置  生成哪些包,放在那里
    PackageConfig pc = new PackageConfig();
    pc.setModuleName("autocode");//项目模块的名字
    pc.setParent("com.hua");//放在这个下面
    pc.setController("contoller");
    pc.setEntity("entity");
    pc.setMapper("mapper");
    pc.setService("service");
    mpg.setPackageInfo(pc);

    //4.策略配置
    StrategyConfig strategy = new StrategyConfig();
    strategy.setInclude("User","likes","course");//设置要映射的表名!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
    strategy.setEntityLombokModel(true);
    //strategy.setRestControllerStyle(true);
    //逻辑删除   逻辑删除的字段名字
    strategy.setLogicDeleteFieldName("deleted");
    //自动填充配置
    TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
    TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
    ArrayList<TableFill> tableFills = new ArrayList<>();
    tableFills.add(gmtCreate);
    tableFills.add(gmtModified);
    strategy.setTableFillList(tableFills);
    //乐观锁
    strategy.setVersionFieldName("version");
    //rest风格
    strategy.setRestControllerStyle(true);
    strategy.setControllerMappingHyphenStyle(true);//localhost:8080/hello_id_2
    mpg.setStrategy(strategy);
    mpg.execute();//执行
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

华华华华华12138

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值