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