快速入门

参考官方文档:https://baomidou.com/guide/

配置日志

  1. #配置日志
  2. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  3. #连接oracle
  4. spring:
  5. spring:
  6. jpa:
  7. database=oracle
  8. datasource:
  9. driver-class-name: oracle.jdbc.driver.OracleDriver
  10. jdbc-url: jdbc:oracle:thin:@localhost:1521:orcl
  11. username: scott
  12. password: 123456
  13. #数据源类型
  14. type: com.alibaba.druid.pool.DruidDataSource
  15. #jdbc:oracle:thin:@10.124.0.42:1521:tact5 其中tact5为数据库的实例名称可连接数据库之后通过在pl/sql中执行select INSTANCE_NAME from v$instance查询
  16. #springboot2以后自动配置需要使用driver-class-name和jdbc-url不然会报错
  17. # 数据源其他配置
  18. initialSize: 5
  19. minIdle: 5
  20. maxActive: 20
  21. maxWait: 60000
  22. timeBetweenEvictionRunsMillis: 60000
  23. minEvictableIdleTimeMillis: 300000
  24. validationQuery: SELECT 1 FROM DUAL
  25. testWhileIdle: true
  26. testOnBorrow: false
  27. testOnReturn: false
  28. poolPreparedStatements: true
  29. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  30. filters: stat,wall,log4j
  31. maxPoolPreparedStatementPerConnectionSize: 20
  32. useGlobalDataSourceStat: true
  33. connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  34. url: jdbc:oracle:thin:@localhost:1521:orcl
  35. webservices:
  36. path: com.sh.service.UserService

JAVA使用

XXXXMapper

  1. public interface UserMapper extends BaseMapper<User> //Pojo类{
  2. }

XXXXService

  1. public interface UserService extends IService<User> //Pojo类{
  2. }

XXXXServiceImpl

  1. @Service
  2. public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
  3. }

CRUD相关操作

插入操作

  1. //测试插入
  2. @Test
  3. public void testInsert(){
  4. User user = new User();
  5. user.setId(43L);
  6. user.setName("time测试");
  7. int result = userMapper.insert(user);
  8. System.out.println(result);
  9. System.out.println(user);
  10. }

主键生成策略

image-20201212000105231.png

主键自增

1、实体类字段加上 @TableId(type = IdType.AUTO)
2、数据库字段设置自增

其余源码解释

  1. AUTO(0), //数据库id自增
  2. NONE(1), //未设置主键
  3. INPUT(2), //手动输入
  4. ID_WORKER(3), //默认全局唯一id
  5. ID_WORKER_STR(3), //ID_WORKER字符串表示法
  6. UUID(4); //全局唯一id uuid

更新操作

  1. //测试更新
  2. @Test
  3. public void testUpdate(){
  4. User user = new User();
  5. //通过条件自动拼接动态sql
  6. user.setId(11L);
  7. user.setName("11111");
  8. //注意:updateById传入的参数是一个对象
  9. int i = userMapper.updateById(user);
  10. System.out.println(i);
  11. }

自动填充

数据库:
image-20201212230237392.png
pojo类:

  1. //pojo类
  2. //字段添加填充内容
  3. @TableField(fill = FieldFill.INSERT)
  4. private Date createTime;
  5. @TableField(fill = FieldFill.INSERT_UPDATE)
  6. private Date updateTime;

handler.MyMetaObjectHandler

  1. package com.cyx.mybatiasplustest.handler;
  2. import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.ibatis.reflection.MetaObject;
  5. import org.springframework.stereotype.Component;
  6. import java.util.Date;
  7. /**
  8. * @author cyx
  9. * @create 2020-12-11 17:13
  10. */
  11. @Slf4j
  12. @Component //一定不要忘记把处理器加到IOC容器中
  13. public class MyMetaObjectHandler implements MetaObjectHandler {
  14. //插入时候的填充策略
  15. @Override
  16. public void insertFill(MetaObject metaObject) {
  17. log.info("start insert fill...");
  18. //setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
  19. this.setFieldValByName("createTime",LocalDateTime.now(),metaObject);
  20. this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
  21. }
  22. //更新时候的填充策略
  23. @Override
  24. public void updateFill(MetaObject metaObject) {
  25. log.info("start update fill...");
  26. this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
  27. }
  28. }

乐观锁

数据库:
image-20201212230249860.png
pojo类:

  1. @Version //乐观锁Version注解
  2. private Integer version;

config.MyBatisPlusConfig

  1. package com.cyx.mybatiasplustest.config;
  2. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
  3. import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
  4. import org.mybatis.spring.annotation.MapperScan;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.transaction.annotation.EnableTransactionManagement;
  8. /**
  9. * @author cyx
  10. * @create 2020-12-11 23:19
  11. */
  12. // 扫描我们的mapper文件夹
  13. @MapperScan("com.cyx.mybatiasplustest.mapper")
  14. @EnableTransactionManagement
  15. @Configuration //配置类
  16. public class MyBatisPlusConfig {
  17. //注册乐观锁插件
  18. @Bean
  19. public MybatisPlusInterceptor mybatisPlusInterceptor(){
  20. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  21. interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
  22. return interceptor;
  23. }
  24. }

test:

  1. //测试乐观锁成功!
  2. @Test
  3. public void testVersion(){
  4. //1、查询用户信息
  5. User user = userMapper.selectById(1L);
  6. //2、修改用户信息
  7. user.setName("cyx");
  8. //3、执行更新操作
  9. userMapper.updateById(user);
  10. }
  11. //测试乐观锁失败!多线程下
  12. @Test
  13. public void testVersion2(){
  14. // 线程1
  15. User user1 = userMapper.selectById(1L);
  16. user1.setName("cyx");
  17. // 模拟另外一个线程执行了插队操作
  18. User user2 = userMapper.selectById(1L);
  19. user2.setName("cyx222");
  20. userMapper.updateById(user2);
  21. userMapper.updateById(user1);// 如果没有乐观锁就会覆盖插队线程的值
  22. }

查询操作

  1. //测试查询
  2. @Test
  3. public void testSelectById(){
  4. User user = userMapper.selectById(1L);
  5. System.out.println(user);
  6. }
  7. //测试批量查询
  8. @Test
  9. public void testSelectByBatchId(){
  10. List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 12));
  11. users.forEach(System.out::println);
  12. }
  13. //条件查询之一 使用map操作
  14. @Test
  15. public void testSelectByBatchIds(){
  16. HashMap<String,Object> map = new HashMap<>();
  17. //自定义查询
  18. map.put("name","cyx222");
  19. map.put("id","1");
  20. List<User> users = userMapper.selectByMap(map);
  21. users.forEach(System.out::println);
  22. }

分页查询

1、配置拦截器组件
config.MyBatisPlusConfig:

  1. @Bean
  2. public PaginationInterceptor paginationInterceptor() {
  3. return new PaginationInterceptor();
  4. }

2、使用Page对象即可

  1. //测试分页查询
  2. @Test
  3. public void testPage(){
  4. //参数一:当前页
  5. //参数二:页面大小
  6. //使用了分页插件之后,所有的分页操作也变得简单
  7. Page<User> page = new Page<>(2,5);
  8. userMapper.selectPage(page,null);
  9. page.getRecords().forEach(System.out::println);
  10. System.out.println(page.getTotal());
  11. }

删除操作

基本的删除操作:

  1. //测试删除
  2. @Test
  3. public void testDeleteById(){
  4. userMapper.deleteById(12);
  5. }
  6. //批量删除
  7. @Test
  8. public void testDeleteBatchId(){
  9. userMapper.deleteBatchIds(Arrays.asList(1,11));
  10. }
  11. //通过Map删除
  12. @Test
  13. public void testDeleteMap(){
  14. HashMap<String, Object> map = new HashMap<>();
  15. map.put("name","1");
  16. userMapper.deleteByMap(map);
  17. }

逻辑删除

物理删除:从数据库中直接删除

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

逻辑删除并没有被真正删除!

1、数据表中增加一个deleted字段
image-20201212230400607.png
2、pojo类:

  1. @TableLogic //逻辑删除
  2. private Integer deleted;

3、设置配置文件

  1. #配置逻辑删除
  2. mybatis-plus:
  3. global-config:
  4. db-config:
  5. logic-delete-value: 1 # 逻辑已删除值(默认为 1)
  6. logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

4、测试
image-20201212231310940.png
记录依旧在数据库,但是deleted变成1。
image-20201212231350455.png

执行查询操作
image-20201212231523053.png

性能分析插件

MP提供性能分析插件,超过时间停止运行。

1、导入插件

参考官方文档

2、测试使用

使用性能分析插件,可以提升效率。

条件构造器

Wrapper:可以替代复杂的SQL语句
测试一:

  1. @Test
  2. void contextLoads() {
  3. // 查询age不为空的,并且id大于10的
  4. QueryWrapper<User> wrapper = new QueryWrapper<>();
  5. wrapper.isNotNull("age")
  6. .ge("id",10);
  7. userMapper.selectList(wrapper).forEach(System.out::println);
  8. }

测试二:

  1. @Test
  2. void test2() {
  3. // 查询名字asd
  4. QueryWrapper<User> wrapper = new QueryWrapper<>();
  5. wrapper.eq("name","asd");
  6. User user = userMapper.selectOne(wrapper);//查询一个数据,出现多个结果使用List或者Map
  7. System.out.println(user);
  8. }

测试三:

  1. @Test
  2. void test3() {
  3. // 查询年龄20-30之间的用户
  4. QueryWrapper<User> wrapper = new QueryWrapper<>();
  5. wrapper.between("age",20,30); //区间
  6. Integer count = userMapper.selectCount(wrapper); //查询结果数
  7. System.out.println(count);
  8. }

测试四:

  1. //模糊查询
  2. @Test
  3. void test4() {
  4. QueryWrapper<User> wrapper = new QueryWrapper<>();
  5. // 左和右 t%
  6. wrapper
  7. .notLike("id","e") // %e%
  8. .likeRight("name","t"); // t%
  9. List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
  10. maps.forEach(System.out::println);
  11. }

测试五:

  1. @Test
  2. void test5() {
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. // id 在子查询中查出来
  5. wrapper.inSql("id","select id from myuser where id<=5");
  6. List<Object> objects = userMapper.selectObjs(wrapper);
  7. objects.forEach(System.out::println);
  8. }

测试六:

  1. @Test
  2. void test6() {
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. // 通过id进行排序
  5. wrapper.orderByDesc("id");
  6. List<User> list = userMapper.selectList(wrapper);
  7. list.forEach(System.out::println);
  8. }

代码自动生成器

dao、pojo、service、controller都是自动生成

1、导入mybatis-plus的包、添加 代码生成器 依赖

2、填写配置

  1. //代码自动生成
  2. public class CodeGenerator {
  3. /**
  4. * <p>
  5. * 读取控制台内容
  6. * </p>
  7. */
  8. // public static String scanner(String tip) {
  9. // Scanner scanner = new Scanner(System.in);
  10. // StringBuilder help = new StringBuilder();
  11. // help.append("请输入" + tip + ":");
  12. // System.out.println(help.toString());
  13. // if (scanner.hasNext()) {
  14. // String ipt = scanner.next();
  15. // if (StringUtils.isNotBlank(ipt)) {
  16. // return ipt;
  17. // }
  18. // }
  19. // throw new MybatisPlusException("请输入正确的" + tip + "!");
  20. // }
  21. public static void main(String[] args) {
  22. // 代码生成器
  23. AutoGenerator mpg = new AutoGenerator();
  24. // 配置策略
  25. // 1、全局配置
  26. GlobalConfig gc = new GlobalConfig();
  27. String projectPath = System.getProperty("user.dir");
  28. gc.setOutputDir(projectPath + "/mybatias-plus-test/src/main/java");
  29. gc.setAuthor("cyx");
  30. gc.setOpen(false);
  31. gc.setFileOverride(false); // 是否覆盖
  32. gc.setServiceName("%sService"); // 去掉Service的I前缀
  33. gc.setIdType(IdType.ID_WORKER);
  34. gc.setDateType(DateType.ONLY_DATE);
  35. //gc.setSwagger2(true); //实体属性 Swagger2 注解
  36. mpg.setGlobalConfig(gc);
  37. // 2、数据源配置
  38. DataSourceConfig dsc = new DataSourceConfig();
  39. dsc.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
  40. dsc.setDriverName("oracle.jdbc.driver.OracleDriver");
  41. dsc.setUsername("scott");
  42. dsc.setPassword("123456");
  43. dsc.setDbType(DbType.ORACLE);
  44. mpg.setDataSource(dsc);
  45. // 3、包配置
  46. PackageConfig pc = new PackageConfig();
  47. pc.setModuleName("blog");
  48. pc.setParent("com.cyx");
  49. pc.setEntity("entity");
  50. pc.setMapper("mapper");
  51. pc.setService("service");
  52. pc.setController("controller");
  53. mpg.setPackageInfo(pc);
  54. // 4、策略配置
  55. StrategyConfig strategy = new StrategyConfig();
  56. strategy.setInclude("MYUSER"); //设置要映射的表名,可以填写多个表名
  57. strategy.setNaming(NamingStrategy.underline_to_camel);
  58. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  59. strategy.setEntityLombokModel(true); // 自动lombok
  60. strategy.setLogicDeleteFieldName("deleted");
  61. // 自动填充配置
  62. TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
  63. TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
  64. ArrayList<TableFill> tableFills = new ArrayList<>();
  65. tableFills.add(gmtCreate);
  66. tableFills.add(gmtModified);
  67. strategy.setTableFillList(tableFills);
  68. // 乐观锁
  69. strategy.setVersionFieldName("version");
  70. strategy.setRestControllerStyle(true);
  71. strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2
  72. mpg.setStrategy(strategy);
  73. mpg.execute(); // 执行
  74. }
  75. }

效果:
image-20201213134500748.png