要快速学习 MyBatis-Plus,可以从以下几个方面入手:
来源chatGPT生成
1. 基础介绍
MyBatis-Plus 是 MyBatis 的增强工具,简化了 MyBatis 的开发,提供了更多的功能和默认实现。它减少了大量的手写 SQL,特别适用于 CRUD 操作。
2. 快速入门
(1) 项目依赖
在 Maven 项目中添加 MyBatis-Plus 依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.0</version> <!-- 根据实际版本调整 -->
</dependency>
(2) 配置数据库连接
在 application.yml
或 application.properties
中配置数据库连接:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username: root
password: your_password
(3) Mapper 接口
定义一个实体类和对应的 Mapper
接口:
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
// Mapper 接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
BaseMapper
提供了通用的 CRUD 方法。
(4) Service 层使用
可以在 Service 层使用 UserMapper
进行数据库操作,常见操作如下:
java复制代码@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
return userMapper.selectList(null); // 查询所有用户
}
public void addUser(User user) {
userMapper.insert(user); // 插入用户
}
}
3. 常用功能
(1) 条件构造器
MyBatis-Plus 提供了丰富的条件构造器,简化复杂 SQL 语句的构建。比如:
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name", "张").ge("age", 18);
List<User> users = userMapper.selectList(queryWrapper);
这段代码相当于:
SELECT * FROM user WHERE name LIKE '%张%' AND age >= 18;
(2) 分页查询
分页查询是常用需求,MyBatis-Plus 提供了简单的分页接口:
java复制代码IPage<User> page = new Page<>(1, 10); // 当前页1,页大小10
IPage<User> result = userMapper.selectPage(page, null);
List<User> users = result.getRecords();
(3) 自动填充
MyBatis-Plus 支持字段的自动填充,比如创建时间、更新时间等:
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
(4) 逻辑删除
配置逻辑删除字段:
@TableLogic
private Integer deleted;
在 application.yml
中配置逻辑删除 SQL 语句:
mybatis-plus:
global-config:
db-config:
logic-delete-value: 1
logic-not-delete-value: 0
4. 代码生成器
MyBatis-Plus 提供了代码生成器,可以自动生成实体类、Mapper、Service、Controller 等代码,大幅提高开发效率。
AutoGenerator generator = new AutoGenerator();
generator.setGlobalConfig(globalConfig);
generator.setDataSource(dataSourceConfig);
generator.setPackageInfo(packageConfig);
generator.setStrategy(strategyConfig);
generator.execute(); // 生成代码
5. 与 Spring 的集成
- MyBatis-Plus 与 Spring Boot 深度集成,使用简单。
- 可以通过
@MapperScan
扫描 Mapper 接口。
@MapperScan("com.example.mapper")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
6. 扩展和高级功能
- 多数据源支持:通过
DynamicDataSource
轻松实现多数据源管理。 - 性能优化插件:MyBatis-Plus 提供了分页、乐观锁等插件,方便集成到项目中。
- 自定义 SQL 支持:如果有复杂业务逻辑,仍然可以手动写 SQL,并结合 MyBatis-Plus 使用。
7. 学习资源
- MyBatis-Plus 官方文档
- 参考代码示例和源码深入理解 MyBatis-Plus 的工作机制。
通过上述步骤,可以快速掌握 MyBatis-Plus 的基本用法和常见功能。