本文代码地址:

https://gitee.com/njitzyd/mybatis-plus

MybatisPlus 特性

  1. 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  2. 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作, BaseMapper
    强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分
    CRUD 操作,更有强大的条件构造器,满足各类使用需求, 以后简单的CRUD操作,它不用自己编写
    了!
  3. 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  4. 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配
    置,完美解决主键问题
  5. 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大
    的 CRUD 操作

快速入门

官方地址 https://mp.baomidou.com/guide/quick-start.html

步骤

1. 数据库准备

  • 创建数据库 mybatis_plus

  • 创建表

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)
);
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');
-- 真实开发中,version(乐观锁)、deleted(逻辑删除)、gmt_create、gmt_modified

2. 创建项目(基于SpringBoot)

  • 导入依赖
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus 并非Spring官方的!,所以命名在前 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>

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

  • 书写配置文件

    # mysql 5 驱动不同 com.mysql.jdbc.Driver
    # mysql 8 驱动不同com.mysql.cj.jdbc.Driver、需要增加时区的配置serverTimezone=GMT%2B8
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?
    useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Drive
    

    这里注意一下:

    如果启动的时候报错,可能就是这个时区的问题,时区配置有两种,都有效serverTimezone=GMT%2B8,serverTimezone=Asia/Shanghai.

3. 书写业务代码

  • 对比传统方案

传统方式pojo-dao(连接mybatis,配置mapper.xml文件)-service-controller

  • pojo

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {private Long id;
    private String name;
    private Integer age;
    private String email;
    }
    
  • mapper接口

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kuang.pojo.User;
import org.springframework.stereotype.Repository;
// 在对应的Mapper上面继承基本的类 BaseMapper
@Repository // 代表持久层
public interface UserMapper extends BaseMapper<User> {// 所有的CRUD操作都已经编写完成了
// 你不需要像以前的配置一大堆文件了!
}
  • 启动类添加注解

    注意点,我们需要在主启动类上去扫描我们的mapper包下的所有接口
    @MapperScan("com.njit.mapper")

  • 测试类中测试

@SpringBootTest
class MybatisPlusApplicationTests {@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {// 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
// 查询全部用户
List<User> users = userMapper.selectList(null);
// Lambda表达式
users.forEach(System.out::println);
}
}
  • 查看结果

4. 配置日志

现在可以看到MybatisPlus帮我们实现类查询,但是无法看到查询语句,如果想要看他如何执行的,就要配置日志!

  • 在配置文件中配置

    mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    
  • 重新运行上面的测试方法,可以看到控制台的语句

配置完毕日志之后,后面的学习就需要注意这个自动生成的SQL,你们就会喜欢上 MyBatis-Plus!

CRUD扩展

插入操作 insert

前言:数据库中逐渐生成的策略

MyBatisPlus支持主键的策略有五种,默认采用ID_WORKER来实现(雪花算法)

public enum IdType {AUTO(0), // 数据库id自增
NONE(1), // 未设置主键
INPUT(2), // 手动输入
ID_WORKER(3), // 默认的全局唯一id
UUID(4), // 全局唯一id uuid
ID_WORKER_STR(5); //ID_WORKER 字符串表示法
}
  • 雪花算法

    默认的采用的就是雪花算法生成,ID_WORKER.

    snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为
    毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味
    着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯
    一!

    使用

    新建一个测试类,新增一条数据

     @Testpublic void testInsert(){User user = new User();user.setName("njitzyd");user.setAge(18);user.setEmail("njitzyd@qq.com");int insert = userMapper.insert(user);System.out.println(insert);System.out.println(user);}
    

可以看到id值是根据雪花算法自动生成的。(注意数据库中表的主键没有设置为自增

  • 主键自增

    主键自增也是一个很常见的策略。

    使用

    先在数据库中把表的主键设置为自增

然后再把pojo的主键上添加注解TableId(type = IdType.AUTO)

运行测试类,可以看到,刚刚是194结尾,现在是195

  • 手动输入(INPUT)一旦设置为手动输入,就必须要自己设置值,不设置就会存入null,即使数据库设置为自增也没有值。

  • 其他两个的使用类似,并不常用

插入补充

  • 设置主键自增后,插入设置主键值的pojo会出现什么状况

结果显示设置的id并没有起效,还是按照自增的策略插入数据的。

更新操作 update

 // 测试更新@Testpublic void testUpdate(){User user = new User();user.setId(7L);user.setName("zzzzzzyyyddd");user.setAge(20);int i = userMapper.updateById(user);}

可以看到sql语句是动态绑定的,也就是我们设置了哪些字段,他生成的sql里面就会有哪些字段

即通过条件自动拼接动态sql

自动填充

创建时间、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新!
阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需
要自动化!

方式一:数据库级别(工作中不允许你修改数据库)

  • 新增两个字段,然后默认值都设置为CURRENT_TIMESTAMP,即当前的时间,update_time勾选更新,及操作时会自动更新


这里需要注意的是,在5.5版本的数据库中是没办法这样设置,在5.7以及以上的版本才能这样设置

  • 实体类新增两个字段

    private Date createTime;
    private Date updateTime;
    

    然后测试更新就会在数据库中看到结果

方式二:代码级别

  • 先把方式一中的设置都取消掉只在数据库中新增两个datetime类型的字段,默认值,更新等都不设置

  • 实体类字段属性上需要增加注解

// 字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
  • 编写处理器来处理这个注解即可!

@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {// 插入时的填充策略@Overridepublic void insertFill(MetaObject metaObject) {log.info("start insert fill.....");
//源码: setFieldValByName(String fieldName, Object fieldVal, MetaObjmetaObjectthis.setFieldValByName("createTime", new Date(), metaObject);this.setFieldValByName("updateTime", new Date(), metaObject);}// 更新时的填充策略@Overridepublic void updateFill(MetaObject metaObject) {log.info("start update fill.....");this.setFieldValByName("updateTime", new Date(), metaObject);}
}

注意这是3.3.0之前的版本,3.3.0之后推荐使用如下的方式

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("start insert fill ....");this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug请升级到之后的版本如`3.3.1.8-SNAPSHOT`)/* 上面选其一使用,下面的已过时(注意 strictInsertFill 有多个方法,详细查看源码) *///this.setFieldValByName("operator", "Jerry", metaObject);//this.setInsertFieldValByName("operator", "Jerry", metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {log.info("start update fill ....");this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug请升级到之后的版本如`3.3.1.8-SNAPSHOT`)/* 上面选其一使用,下面的已过时(注意 strictUpdateFill 有多个方法,详细查看源码) *///this.setFieldValByName("operator", "Tom", metaObject);//this.setUpdateFieldValByName("operator", "Tom", metaObject);}
}
  • 测试
    // 测试更新@Testpublic void testUpdate(){User user = new User();user.setId(1260056765047816197L);user.setName("测试自动填充");user.setAge(20);int i = userMapper.updateById(user);}

因为是更新操作,所以只有更新时间,这时如果新增则创建时间和更新时间都会有值。

乐观锁

有关乐观锁的可以看看我的另一篇笔记乐观锁与悲观锁

乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败
乐观锁:1、先查询,获得版本号 version = 1
-- A 线程
update user set name = "njittt", version = version + 1
where id = 2 and version = 1
-- B 线程抢先完成,这个时候 version = 2,会导致 A 修改失败!
update user set name = "njiiiii", version = version + 1
where id = 2 and version = 1

使用三步骤

  1. 给数据库中增加version字段!

  1. 给实体字段添加@version注解
@Version //乐观锁Version注解
private Integer version;

特别说明:

  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity
  • 仅支持 updateById(id)update(entity, wrapper) 方法
  • update(entity, wrapper) 方法下, wrapper 不能复用!!!

补充上面最后一点wrapper不能复用的理解

/*** 先执行的修改方法的运行结果:* SQL:* SQL: UPDATE user SET email=?, update_time=?, version=? WHERE name = ? AND age = ? AND version = ?* 数据:12736902@123.com(String), 2019-11-01T09:11:35.526(LocalDateTime), 4(Integer), 王天风(String), 25(Integer), 3(Integer)* 结果分析:* 这是更新成功的,返回的影响条数为一,并且将当前的版本好改成了旧的版本号加一** 复用了第一个修改方法的条件构造器的修改方法运行结果:* SQL:UPDATE user SET email=?, update_time=?, version=? WHERE name = ? AND age = ? AND version = ? AND name = ? AND age = ? AND version = ?* 数据:12736902@123.com(String), 2019-11-01T09:11:35.526(LocalDateTime), 5(Integer), 王天风(String), 25(Integer), 3(Integer), 王天风(String), 25(Integer), 4(Integer)* 结果分析:* 可以看到SQL语句中的version = ? AND name = ? AND age = ? AND version = ?,同时判断了两个版本号,所以这条SQL是执行不成功的* 返回的影响条数为0**/
@Test
void optimisticLock02 () {//这个测试方法演示的是乐观锁的注意事项之在update(entity,wrapper)方法下wrapper不能复用//实现方式://1.创建一个User对象,在User对象中传入对应的主键,版本号,和要修改的字段值//2.创建条件构造器设置更新条件//3.mapper调用方法修改记录//4.再创建一个User对象,在User对象中传入对应的主键,版本号(这个版本号即为上一条记录的版本好加一)和要修改的字段值//5.mapper调用方法修改记录User u01 = new User();u01.setId(1088248166370832385L);//方便测直接设置版本号u01.setVersion(3);u01.setEmail("12736902@123.com");QueryWrapper<User> wrapper = Wrappers.query();wrapper.eq("name","王天风").eq("age",25);int rows01 = mapper.update(u01, wrapper);log.info("第一个更新方法的影响条数:"+rows01);User u02 = new User();u02.setVersion(4);u02.setEmail("wtf@baomidou.com");wrapper.eq("name","王天风").eq("age",25);int rows02 = mapper.update(u01, wrapper);log.info("第二个更新方法的影响条数:"+rows02);
}
  1. 注册组件
@Configuration // 配置类
public class MyBatisPlusConfig {// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();
}
}
  1. 测试
    //测试乐观锁成功!@Testpublic void testOptimisticLocker() {// 1、查询用户信息User user = userMapper.selectById(1L);// 2、修改用户信息user.setName("JPQ");user.setEmail("123456789@qq.com");// 3、执行更新操作userMapper.updateById(user);}

会发现修改的条数为一条,然后之前数据库中的version由1变成2.

   // 测试乐观锁失败!多线程下@Testpublic void testOptimisticLocker2() {// 线程 1User user = userMapper.selectById(1L);user.setName("JPQKA");user.setEmail("qqaz@qq.com");// 模拟另外一个线程执行了插队操作User user2 = userMapper.selectById(1L);user2.setName("123456789");user2.setEmail("azqq@qq.com");userMapper.updateById(user2);userMapper.updateById(user); // 如果没有乐观锁就会覆盖插队线程的值!}}

可以发现最后的修改user并没有进行修改,因为version检查的时候不对,无法进行正确的更新。数据库中也是user2正常的更新了。

查询操作 select

   // 测试查询
@Test
public void testSelectById(){User user = userMapper.selectById(1L);System.out.println(user);
} // 测试批量查询!
@Test
public void testSelectByBatchId(){List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));users.forEach(System.out::println);
} // 按条件查询之一使用map操作@Test
public void testSelectByBatchIds(){HashMap<String, Object> map = new HashMap<>();// 自定义要查询map.put("name","狂神说Java");map.put("age",3);List<User> users = userMapper.selectByMap(map);users.forEach(System.out::println);
}

分页查询

1、原始的 limit 进行分页
2、pageHelper 第三方插件
3、MP 其实也内置了分页插件!

如何使用

  • 配置拦截器插件,在刚刚的配置类中新增加一个bean
     @Beanpublic PaginationInterceptor paginationInterceptor() {return  new PaginationInterceptor();}
  • 直接使用Page对象
// 测试分页查询
@Test
public void testPage(){// 参数一:当前页// 参数二:页面大小// 使用了分页插件之后,所有的分页操作也变得简单的!Page<User> page = new Page<>(2,5);userMapper.selectPage(page,null);page.getRecords().forEach(System.out::println);System.out.println(page.getTotal());
}

这里需要注意下分页都会在开始查询时先查询总条数

删除操作 delete

根据id删除

 // 测试删除@Testpublic void testDeleteById() {userMapper.deleteById(1240620674645544965L);}// 通过id批量删除@Testpublic void testDeleteBatchId() {userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L, 1240620674645544962L));}// 通过map删除@Testpublic void testDeleteMap() {HashMap<String, Object> map = new HashMap<>();map.put("name", "Tom");userMapper.deleteByMap(map);}

逻辑删除

使用mp自带方法删除和查找都会附带逻辑删除功能 (自己写的xml不会)

物理删除 :从数据库中直接移除
逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1

具体使用:

  • 在数据表中新增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
  • 测试
 // 测试逻辑删除
@Test
public void testLogicDeleteById() {userMapper.deleteById(1260056765047816194L);
}

可以看到数据库中的变化如下:

  • 再次查询
  // 测试查询
@Test
public void testSelectById() {User user = userMapper.selectById(1260056765047816194LL);
}

会发现这条记录已经查不到了。

逻辑删除补充

从3.3.0开始,官网又推出了全局逻辑删除(注意版本3.3.0开始

如果公司代码比较规范,比如统一了全局都是flag为逻辑删除字段。

使用此配置则不需要在实体类上添加 @TableLogic。

但如果实体类上有 @TableLogic 则以实体上的为准,忽略全局。 即先查找注解再查找全局,都没有则此表没有逻辑删除。

mybatis-plus:global-config:db-config:logic-delete-field: flag  #全局逻辑删除字段值

附件说明

  • 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。
  • 如果你需要再查出来就不应使用逻辑删除,而是以一个状态去表示。

如: 员工离职,账号被锁定等都应该是一个状态字段,此种场景不应使用逻辑删除。

  • 若确需查找删除数据,如老板需要查看历史所有数据的统计汇总信息,请单独手写sql。

性能分析插件

我们在平时的开发中,会遇到一些慢sql。测试! druid,

MP也提供性能分析插件,如果超过这个时间就停止运行!

作用:性能分析拦截器,用于输出每条 SQL 语句及其执行时间

  • 配置
   /*** SQL执行效率插件*/
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {PerformanceInterceptor performanceInterceptor = new
PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // ms设置sql执行的最大时间,如果超过了则不
执行
performanceInterceptor.setFormat(true); // 是否格式化代码
return performanceInterceptor;
}

注意!参数说明:

  • 参数:maxTime SQL 执行最大时长,超过自动停止运行,有助于发现问题。
  • 参数:format SQL SQL是否格式化,默认false。
  • 该插件只用于开发环境,不建议生产环境使用。
  • 在springboot中配置环境为dec或者test
spring.profiles.active=dev
  • 测试
@Test
void contextLoads() {// 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
// 查询全部用户
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}

性能分析插件补充

性能分析插件在 3.2.0 以上版本移除推荐使用第三方扩展 执行SQL分析打印 功能

执行SQL分析打印

该功能依赖 p6spy 组件,完美的输出打印 SQL 及执行时长 3.1.0 以上版本

  • 添加p6spy依赖
<dependency><groupId>p6spy</groupId><artifactId>p6spy</artifactId><version>最新版本</version>
</dependency>
  • application.yml 配置
spring:datasource:driver-class-name: com.p6spy.engine.spy.P6SpyDriverurl: jdbc:p6spy:h2:mem:test...

spy.properties 配置:

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,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

注意!

  • driver-class-name 为 p6spy 提供的驱动类
  • url 前缀为 jdbc:p6spy 跟着冒号为对应数据库连接地址
  • 打印出sql为null,在excludecategories增加commit
  • 批量操作不打印sql,去除excludecategories中的batch
  • 批量操作打印重复的问题请使用MybatisPlusLogFactory (3.2.1新增)
  • 该插件有性能损耗,不建议生产环境使用。

条件构造器

我们写一些复杂的sql就可以使用它来替代! ,在运行时可以看看他的sql的语法

 @Testvoid contextLoads() {// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.isNotNull("name").isNotNull("email").ge("age", 12);userMapper.selectList(wrapper).forEach(System.out::println); // 和我们刚才学习的map对比一下}@Testvoid test2() {// 查询名字njitzydQueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.eq("name", "njitzyd");User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List或者 MapSystem.out.println(user);}@Testvoid test3() {// 查询年龄在 20 ~ 30 岁之间的用户QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.between("age", 20, 30); // 区间Integer count = userMapper.selectCount(wrapper);// 查询结果数System.out.println(count);}//模糊查询@Testvoid test4() {// 查询年龄在 20 ~ 30 岁之间的用户QueryWrapper<User> wrapper = new QueryWrapper<>();// 左和右 :右就是->t%wrapper.notLike("name", "e").likeRight("email", "t");List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);maps.forEach(System.out::println);}// 模糊查询@Testvoid test5() {QueryWrapper<User> wrapper = new QueryWrapper<>();// id 在子查询中查出来wrapper.inSql("id", "select id from user where id<3");List<Object> objects = userMapper.selectObjs(wrapper);objects.forEach(System.out::println);}//测试六@Testvoid test6() {QueryWrapper<User> wrapper = new QueryWrapper<>();// 通过id进行排序wrapper.orderByAsc("id");List<User> users = userMapper.selectList(wrapper);users.forEach(System.out::println);}// 测试7 使用lambdaQueryWrapper@Testvoid test7() {LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();// 通过id进行排序wrapper.eq(User::getAge, 18);List<User> users = userMapper.selectList(wrapper);users.forEach(System.out::println);}

代码生成器

dao、pojo、service、controller都给我自己去编写完成!
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、
Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

velocity模板引擎(默认)

需要注意的点:mybatis-plus在3.0.3之后默认移除了代码生成器以及模板引擎,默认是使用velocity,使用其他的需要单独的指定,
所以我们要添加下面两个依赖:

generate代码:


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;public class Generator {public static void main(String[] args) {//创建generator对象AutoGenerator autoGenerator = new AutoGenerator();//数据源DataSourceConfig dataSourceConfig =new DataSourceConfig();dataSourceConfig.setDbType(DbType.MYSQL);dataSourceConfig.setUrl("jdbc:mysql://xxxx:3306/wkms?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8");dataSourceConfig.setUsername("xxxx");dataSourceConfig.setPassword("xxxx!@");dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");autoGenerator.setDataSource(dataSourceConfig);//全局配置GlobalConfig globalConfig = new GlobalConfig();//输出到那个目录globalConfig.setOutputDir(System.getProperty("user.dir") + "\\zyd-module-dal\\src\\main\\java");//生成之后是否打开文件夹globalConfig.setOpen(false);globalConfig.setAuthor("xxx");globalConfig.setFileOverride(true);globalConfig.setEntityName("%sEntity");globalConfig.setServiceName("%sDao");globalConfig.setDateType(DateType.ONLY_DATE);autoGenerator.setGlobalConfig(globalConfig);//配置模板TemplateConfig templateConfig = new TemplateConfig();templateConfig.setXml(null);templateConfig.setService(null);templateConfig.setServiceImpl(null);templateConfig.setController(null);// 自定service 使用的模板 这样配置就必须在 resources下// 存在 dao.vm (vm这个后缀取决于你的模板引擎),不存在的话 你的 Service就不会生成templateConfig.setService("/dao");autoGenerator.setTemplate(templateConfig);//包信息PackageConfig packageConfig = new PackageConfig();packageConfig.setParent("com.weimob.arch");// 会在上面setParent 后拼上moduleName生成整体包名packageConfig.setModuleName("weimobkms.dal");packageConfig.setMapper("mapper");packageConfig.setEntity("entity");packageConfig.setService("dao");autoGenerator.setPackageInfo(packageConfig);//配置策略StrategyConfig strategyConfig = new StrategyConfig();// 指定你要生成的表,默认 是当前连接的所有表
//        strategyConfig.setInclude("sub_biz_key", "sub_biz_key_version");strategyConfig.setEntityLombokModel(false);//设置驼峰命名,可以自动将数据库中的下划线方式转换成驼峰的形式,如user_name--->userNamestrategyConfig.setNaming(NamingStrategy.underline_to_camel);strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);strategyConfig.setChainModel(true);autoGenerator.setStrategy(strategyConfig);autoGenerator.execute();}
}

dao.vm代码如下

package ${package.Service};import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;/*** <p>* $!{table.comment} 表的服务实现类* </p>** @author ${author}* @since ${date}*/
@Service
@Slf4j
public class ${table.serviceName} extends ServiceImpl<${table.mapperName}, ${entity}> {}

freemmarker模板引擎

需要注意的点:mybatis-plus在3.0.3之后默认移除了代码生成器以及模板引擎,所以我们要添加下面两个依赖

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.2</version>
</dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.30</version>
</dependency>

然后编写代码:

/*** @ClassName GenerateCode* @Description TODO* @auther zhuyoude* @Date 2020/5/15 13:42* @Version 1.0**/
// 代码自动生成器
public class GenerateCode {public static void main(String[] args) {// 需要构建一个 代码自动生成器 对象AutoGenerator mpg = new AutoGenerator();// 配置策略// 1、全局配置GlobalConfig gc = new GlobalConfig();// 这里要注意如果只是user.dir,那么在多模块的项目中就会在父模块中生成,所以后面要指定那个模块String projectPath = System.getProperty("user.dir")+"/mybatis-plus-autogenerator";gc.setOutputDir(projectPath + "/src/main/java");gc.setAuthor("njitzyd");gc.setOpen(false);gc.setFileOverride(false); // 是否覆盖gc.setServiceName("%sService"); // 去Service的I前缀gc.setIdType(IdType.AUTO); //设置自增长gc.setDateType(DateType.ONLY_DATE);gc.setSwagger2(true);mpg.setGlobalConfig(gc);//2、设置数据源DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("root");dsc.setDbType(DbType.MYSQL);mpg.setDataSource(dsc);//3、包的配置PackageConfig pc = new PackageConfig();
//        pc.setModuleName("mybatis-plus-autogenerator");pc.setParent("com.njit");pc.setEntity("entity");pc.setMapper("mapper");pc.setService("service");pc.setController("web");mpg.setPackageInfo(pc);//4、策略配置StrategyConfig strategy = new StrategyConfig();strategy.setInclude("user"); // 设置要映射的表名strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);strategy.setEntityLombokModel(true); // 自动lombok;//数据库表:sts_dept  需要去掉:sts_ 表前缀可以在策略类添加此属性:// strategy.setTablePrefix("sts_");// 5、设置模板引擎 freemarker enginempg.setTemplateEngine(new FreemarkerTemplateEngine());// 乐观锁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");strategy.setRestControllerStyle(true);strategy.setControllerMappingHyphenStyle(true); //localhost:8080 / hello_id_2mpg.setStrategy(strategy);mpg.execute(); //执行}}

然后查看项目就可以发现已经创建好!

Mybatis-Plus教程相关推荐

  1. mybatis实战教程(mybatis in action),mybatis入门到精通

     目录(?) [-] mybatis实战教程mybatis in action之一开发环境搭建 mybatis实战教程mybatis in action之二以接口的方式编程 mybatis实战教程 ...

  2. springboot整合mysql5.7_详解SpringBoot整合MyBatis详细教程

    1. 导入依赖 首先新建一个springboot项目,勾选组件时勾选Spring Web.JDBC API.MySQL Driver 然后导入以下整合依赖 org.mybatis.spring.boo ...

  3. 视频教程-MyBatis简明教程-Java

    MyBatis简明教程 就职于国内知名在线互联网旅游公司,10+互联网开发经验,精通前后端开发 刘志强 ¥29.00 立即订阅 扫码下载「CSDN程序员学院APP」,1000+技术好课免费看 APP订 ...

  4. 一起学 mybatis 基础教程

    我也才刚刚开始学习mybatis 有很多不懂得地方和大家探讨,准备把我自己学习mybatis的一些心得和大家分享. mybatis 基本教程 mybatis + maven 环境搭建 mybatis ...

  5. Spring+SpringMVC+MyBatis整合教程

    2019独角兽企业重金招聘Python工程师标准>>> 1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框 ...

  6. mybatis实战教程(mybatis in action),mybatis入门到精通(转)

    写在这个系列前面的话: 以前曾经用过ibatis,这是mybatis的前身,当时在做项目时,感觉很不错,比hibernate灵活.性能也比hibernate好.而且也比较轻量级,因为当时在项目中,没来 ...

  7. mybatis学习教程(二)初级的增、删、查、改

    引言 本文主要从一个基础实例,讲解Mybatis的实现,已经每一步的详细讲解.我会将项目共享在百度云盘,文章最后! 1.项目结构 2.项目配置  2.1 配置SqlMapConfig.xml 根据My ...

  8. mybatis crud_MyBatis教程– CRUD操作和映射关系–第1部分

    mybatis crud CRUD操作 MyBatis是一个SQL Mapper工具,与直接使用JDBC相比,它极大地简化了数据库编程. 步骤1:创建一个Maven项目并配置MyBatis依赖项. & ...

  9. mybatis crud_MyBatis教程– CRUD操作和映射关系–第2部分

    mybatis crud 为了说明这一点,我们正在考虑以下示例域模型: 会有用户,每个用户可能都有一个博客,每个博客可以包含零个或多个帖子. 这三个表的数据库结构如下: CREATE TABLE us ...

  10. idea 配置springmvc+mybatis(图文教程)

    idea配置 spirngmvc+maven+mybatis 数据库采用的是mysql  服务器容器用的是tomcat8 废话不多说直接干! 首先新建一个 maven工程, "File&qu ...

最新文章

  1. Java print流简介
  2. Prototype原型模式(创建型模式)
  3. 数据结构(五)层次遍历
  4. lime 模型_使用LIME的糖尿病预测模型解释— OneZeroBlog
  5. android开发学习——Mina框架
  6. 超全机器学习工程师成长路线图,GitHub已收获6400+Star!
  7. 使用PyCharm快速安装TensorFlow
  8. 团队协助 开源项目_5分钟了解 Vtiger CRM-国际知名开源客户管理软件
  9. MySQL 常用函数大全
  10. DataGridView列自适应宽度
  11. 论文阅读笔记 | 分类网络——ParNet
  12. 【番外篇】利率二叉树模型对冲
  13. linux 桌面美化指南,Linux_9方面立体式地美化Ubuntu桌面,总结了一下桌面美化的设置。 - phpStudy...
  14. 元宇宙007 | 沉浸式家庭治疗,让治疗像演情景剧一样!
  15. java 字符串中取消换行或添加换行
  16. 用jar包生成maven依赖
  17. ROS中一个关于时间的函数
  18. CStyle足迹:一个BIOS人的成长日记之开篇
  19. 二十四、冷战和消费主义
  20. 2021 46届icpc 南京

热门文章

  1. 入职两年申请涨薪3K被拒,是我平时好脸给多了?转身立马裸辞走人...
  2. 王者荣耀高清壁纸脚本Python文件
  3. 用 matplotlib 绘制 3D 时间序列动态图
  4. 如何进行文献检索和阅读(转)
  5. Android4.1 如何实现状态栏上信号图标有SIM卡1,2标记,并且当处于2G状态显示“G”,处于3G状态显示“3G”
  6. hta 北京自动挂号器
  7. PPT如何直接转换为word
  8. MFC Windows 程序设计[323]之噪声特征流显示gribble2(附源码)
  9. Python中常用最神秘的函数! lambda 函数深度总结!
  10. 修改人人商城服务器时间,修改收货地址 · 人人商城二次开发常用文档,超详细,微擎开发微擎二次开发【持续更新】 · 看云...