Quantcast
Channel: 小蓝博客
Viewing all articles
Browse latest Browse all 3145

MyBatis-Plus高级用法:最优化持久层开发

$
0
0

MyBatis-Plus高级用法:最优化持久层开发

MyBatis-Plus 是 MyBatis 的增强工具,旨在简化开发、提高效率并保持 MyBatis 的灵活性。本文将详细介绍 MyBatis-Plus 的高级用法,帮助开发者最优化持久层开发。

一、MyBatis-Plus 简介

MyBatis-Plus 是一个 ORM 框架,提供了 CRUD 接口、条件构造器、代码生成器等功能,简化了常见的持久层开发工作。

核心功能

  • CRUD 接口:简单的增删改查操作。
  • 条件构造器:动态生成 SQL 查询条件。
  • 分页插件:简化分页查询操作。
  • 逻辑删除:轻松实现软删除功能。
  • 代码生成器:自动生成实体类、Mapper 接口等代码。

二、快速入门

1. 添加依赖

pom.xml 中添加 MyBatis-Plus 依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3.4</version>
</dependency>

2. 配置数据源

application.yml 中配置数据源:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

3. 创建实体类

创建一个实体类 User

@Data
@TableName("user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

4. 创建 Mapper 接口

创建 Mapper 接口并继承 BaseMapper

public interface UserMapper extends BaseMapper<User> {
}

5. 编写服务类

编写服务类使用 UserMapper

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }
}

6. 编写控制器

编写控制器调用服务类:

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List<User> list() {
        return userService.getAllUsers();
    }
}

三、高级用法

1. 条件构造器

MyBatis-Plus 提供了 QueryWrapperUpdateWrapper 用于动态构造查询和更新条件。

1.1 QueryWrapper

QueryWrapper 用于构建查询条件:

QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "John");
List<User> users = userMapper.selectList(queryWrapper);

1.2 UpdateWrapper

UpdateWrapper 用于构建更新条件:

UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name", "John").set("age", 30);
userMapper.update(null, updateWrapper);

2. 分页插件

分页插件简化了分页查询:

@Autowired
private UserMapper userMapper;

public IPage<User> getUsersByPage(int pageNum, int pageSize) {
    Page<User> page = new Page<>(pageNum, pageSize);
    return userMapper.selectPage(page, null);
}

3. 逻辑删除

逻辑删除不删除数据,只是标记为已删除。首先在实体类中配置逻辑删除字段:

@TableLogic
private Integer deleted;

application.yml 中启用逻辑删除:

mybatis-plus:
  global-config:
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0

使用时直接调用 deleteById 方法即可:

userMapper.deleteById(1L);

4. 代码生成器

代码生成器自动生成实体类、Mapper 接口、Service 类和 Controller 类。以下是代码生成器的简单示例:

@Data
public class CodeGenerator {
    public static void main(String[] args) {
        AutoGenerator autoGenerator = new AutoGenerator();

        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mydb");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("root");
        autoGenerator.setDataSource(dataSourceConfig);

        // 包名配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example.demo");
        autoGenerator.setPackageInfo(packageConfig);

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setInclude("user"); // 表名
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        autoGenerator.setStrategy(strategyConfig);

        autoGenerator.execute();
    }
}

5. 自定义 SQL 注入器

可以自定义 SQL 注入器,实现个性化需求。例如,添加一个批量插入的方法:

@Component
public class MySqlInjector extends AbstractSqlInjector {
    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        methodList.add(new InsertBatchSomeColumn());
        return methodList;
    }
}

四、最佳实践

1. 分层架构

建议遵循分层架构,将控制器、服务、数据访问层分开,提高代码的可维护性。

2. 统一异常处理

使用 @ControllerAdvice 统一处理异常,提升系统的健壮性。

3. 使用事务管理

在服务层使用 @Transactional 注解管理事务,确保数据一致性:

@Transactional
public void updateUser(User user) {
    userMapper.updateById(user);
}

4. 性能优化

  • 使用批量操作:对于大批量数据操作,使用 MyBatis-Plus 提供的批量操作接口,提高性能。
  • 索引优化:确保数据库中相关表和字段有适当的索引,提升查询性能。

五、总结

MyBatis-Plus 通过简化常见的持久层开发任务,提高了开发效率和代码的可维护性。通过合理使用条件构造器、分页插件、逻辑删除和代码生成器等高级功能,可以进一步优化持久层开发,提升系统性能和稳定性。掌握这些高级用法和最佳实践,有助于开发者构建高效、稳定和可扩展的企业级应用。


Viewing all articles
Browse latest Browse all 3145

Trending Articles