云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

如何在Spring Boot项目中整合MyBatis-Plus?

jxf315 2024-12-25 12:44:35 教程文章 31 ℃

MyBatis-Plus是一个MyBatis的增强版工具,简化了MyBatis的操作,提高了开发效率。下面我们就来看看如何在Spring Boot中集成MyBatis-Plus,通过MyBatis-Plus提供的自动配置机制来提高开发效率。

引入MyBatis-Plus依赖

首先,想要使用MyBatis-Plus就需要在项目中集成MyBatis-Plus与MyBatis的依赖配置,如下所示。

<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- MyBatis-Plus Starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.3</version>  <!-- 请根据需要修改为最新版本 -->
    </dependency>

    <!-- MySQL Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

在使用的时候,需要注意Spring Boot的版本与MyBatis-Plus版本的兼容性,可以参考相关的官方文档。

添加依赖完成之后,接下来就需要在配置文件中配置MyBatis-Plus相关的连接配置信息,如下所示。

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_plus_demo?useUnicode=true&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
  mybatis-plus:
    # 设置 Mapper 接口扫描路径
    mapper-locations: classpath:mapper/*.xml
    # 设置 MyBatis-Plus 的实体扫描路径
    typeAliasesPackage: com.example.mybatisplusdemo.entity

配置完成之后,接下来就看看如何使用MyBatis-Plus。

创建实体类

这里我们创建一个User用户实体类,与数据库中的用户信息表进行ORM映射匹配。

@Data
@TableName("user")  // 表示该实体类对应的数据库表是 user
public class User {

    @TableId  // 主键注解
    private Long id;

    private String name;

    private Integer age;

    private String email;
}

创建Mapper接口

在Mybatis-Plus中会根据Mapper接口默认实现一些CRUD的操作,所以一般我们不需要在去编写这些操作的XML配置文件来进行SQL的编写操作,如下所示,我们可以直接通过继承BaseMapper来实现CRUD操作。

@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 继承 BaseMapper 后,所有基本的 CRUD 操作都可以直接使用
}

创建Service层

接下来就是调用Mapper层提供的方法来实现Service层的操作支持,如下所示。

@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    // 此时 UserService 继承自 ServiceImpl,自动具备了常见的业务逻辑
}

接下来就是创建Controller层的操作,来调用Service层的方法进行CRUD方法操作,如下所示。

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 查询所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }

    // 添加用户
    @PostMapping
    public boolean addUser(@RequestBody User user) {
        return userService.save(user);
    }

    // 更新用户
    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

    // 根据 ID 查询用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.removeById(id);
    }
}

这个样就完成了简单的API接口的编写,当然在MyBatis-Plus中还提供了一些扩展的功能,例如分页查询、条件查询等等。

MyBatis-Plus提供的其他特性

分页查询

在MyBatis-Plus中提供了默认的分页操作的插件,我们可以通过这些插件操作来实现分页,如下所示。

mybatis-plus:
  configuration:
    plugins:
      - com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor

然后再Service层中通过调用Page对象来实现分页查询操作。

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

public Page<User> getUsersPage(int page, int size) {
    Page<User> userPage = new Page<>(page, size);
    return userMapper.selectPage(userPage, null);
}

条件构造器

在MyBatis-Plus中还提供了基于条件的构造器来实现复杂条件的查询操作,如下所示,我们可以查询18岁的用户列表。

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("age", 18);
List<User> userList = userMapper.selectList(queryWrapper);

自动填充字段

MyBatis-Plus还提供了自动字段填充功能里,例如对于操作创建时间、更新时间等默认字段都可以通过如下的操作来实现自动填充。

@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;

总结

上面的操作中我们展示了如何在Spring Boot中整合MyBatis-Plus来简化MyBatis的数据操作,通过MyBatis-Plus提供的自动操作我们可以轻松实现自动 CRUD 操作、分页查询、条件构造器等操作,极大的提升了开发效率,开发者可以根据项目灵活的进行调整。

最近发表
标签列表