找回密码
 立即注册
首页 业界区 安全 MyBatis-Plus实战:Spring Boot数据库操作效率提升10倍 ...

MyBatis-Plus实战:Spring Boot数据库操作效率提升10倍

副我 8 小时前
前言

MyBatis-Plus(MP)是 MyBatis 的增强工具,无需编写 SQL 即可完成 CRUD 操作,极大提升开发效率。本文带你实战 Spring Boot 整合 MyBatis-Plus。
一、引入依赖
  1. <dependency>
  2.     <groupId>com.baomidou</groupId>
  3.     mybatis-plus-boot-starter</artifactId>
  4.     <version>3.5.5</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>mysql</groupId>
  8.     mysql-connector-java</artifactId>
  9. </dependency>
  10. # application.yml
  11. spring:
  12.   datasource:
  13.     url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8
  14.     username: root
  15.     password: 123456
  16.     driver-class-name: com.mysql.cj.jdbc.Driver
  17. mybatis-plus:
  18.   configuration:
  19.     log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  20.   global-config:
  21.     db-config:
  22.       logic-delete-field: deleted
  23.       logic-delete-value: 1
  24.       logic-not-delete-value: 0
复制代码
二、实体类
  1. @Data
  2. @TableName("user")
  3. public class User {
  4.     @TableId(type = IdType.AUTO)
  5.     private Long id;
  6.     @TableField("username")
  7.     private String username;
  8.     private String email;
  9.     private Integer age;
  10.     @TableLogic  // 逻辑删除
  11.     private Integer deleted;
  12.     @TableField(fill = FieldFill.INSERT)
  13.     private LocalDateTime createTime;
  14.     @TableField(fill = FieldFill.INSERT_UPDATE)
  15.     private LocalDateTime updateTime;
  16. }
复制代码
三、Mapper 接口
  1. @Mapper
  2. public interface UserMapper extends BaseMapper<User> {
  3.     // 继承 BaseMapper 后,自动拥有以下方法:
  4.     // - insert(entity)
  5.     // - deleteById(id)
  6.     // - updateById(entity)
  7.     // - selectById(id)
  8.     // - selectList(wrapper)
  9.     // - selectPage(page, wrapper)
  10.     // 无需编写 XML!
  11. }
复制代码
四、条件构造器
  1. // 查询年龄大于18且邮箱不为空的用户
  2. List<User> users = userMapper.selectList(
  3.     new LambdaQueryWrapper<User>()
  4.         .gt(User::getAge, 18)
  5.         .isNotNull(User::getEmail)
  6.         .orderByDesc(User::getCreateTime)
  7. );
  8. // 模糊查询
  9. List<User> users = userMapper.selectList(
  10.     new LambdaQueryWrapper<User>()
  11.         .likeRight(User::getUsername, "张")
  12.         .between(User::getAge, 20, 30)
  13. );
  14. // 更新:年龄大于30的用户状态改为1
  15. userMapper.update(null,
  16.     new LambdaUpdateWrapper<User>()
  17.         .set(User::getStatus, 1)
  18.         .gt(User::getAge, 30)
  19. );
复制代码
五、分页查询
  1. // 分页配置类
  2. @Configuration
  3. public class MyBatisPlusConfig {
  4.     @Bean
  5.     public MybatisPlusInterceptor mybatisPlusInterceptor() {
  6.         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  7.         interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  8.         return interceptor;
  9.     }
  10. }
  11. // 分页查询
  12. Page<User> page = new Page<>(1, 10);  // 第1页,每页10条
  13. userMapper.selectPage(page,
  14.     new LambdaQueryWrapper<User>()
  15.         .gt(User::getAge, 18)
  16. );
  17. List<User> records = page.getRecords();  // 当前页数据
  18. long total = page.getTotal();           // 总记录数
  19. long pages = page.getPages();           // 总页数
复制代码
六、代码生成器
  1. // AutoGenerator 一键生成 Entity、Mapper、Service、Controller
  2. AutoGenerator generator = new AutoGenerator();
  3. // 全局配置
  4. GlobalConfig globalConfig = new GlobalConfig();
  5. globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
  6. globalConfig.setAuthor("myname");
  7. globalConfig.setOpen(false);
  8. generator.setGlobalConfig(globalConfig);
  9. // 数据源配置
  10. DataSourceConfig dataSourceConfig = new DataSourceConfig.Builder(
  11.     "jdbc:mysql://localhost:3306/mydb",
  12.     "root", "123456"
  13. ).build();
  14. generator.setDataSource(dataSourceConfig);
  15. // 策略配置
  16. StrategyConfig strategyConfig = new StrategyConfig.Builder()
  17.     .addInclude("user", "order")  // 表名
  18.     .entityBuilder().enableLombok()
  19.     .controllerBuilder().enableRestStyle()
  20.     .build();
  21. generator.setStrategy(strategyConfig);
  22. generator.execute();
复制代码
总结

MyBatis-Plus 让数据库操作变得简单高效。核心要点:BaseMapper 提供开箱即用的 CRUD、LambdaWrapper 类型安全的条件构造、内置分页插件、代码生成器大幅提升效率。

觉得有帮助请点赞收藏!有问题欢迎评论区交流
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册