Spring Boot集成MyBatis-Plus的详细步骤

在Spring Boot中集成MyBatis-Plus是一个常见的需求,因为MyBatis-Plus不仅继承了MyBatis的优点,还提供了许多增强功能,如CRUD操作的简化、分页插件等。


1. 添加依赖

pom.xml文件中添加MyBatis-Plus和数据库驱动的依赖。以MySQL为例:

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

    <!-- MyBatis-Plus Starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.3</version> <!-- 请根据需要选择合适的版本 -->
    </dependency>

    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- Spring Boot Starter Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2. 配置数据源和MyBatis-Plus

application.ymlapplication.properties文件中配置数据源和MyBatis-Plus的相关参数。

application.yml示例:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.yourproject.entity
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  • datasource:配置数据库连接信息。

  • mapper-locations:指定Mapper XML文件的路径。

  • type-aliases-package:指定实体类所在的包路径。

  • log-impl:开启MyBatis日志输出。


3. 创建实体类(Entity)

创建一个实体类,映射数据库表。例如,假设有一个user表:

package com.example.yourproject.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

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

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

4. 创建Mapper接口

创建一个Mapper接口,继承BaseMapper。MyBatis-Plus会自动实现基本的CRUD操作。

package com.example.yourproject.mapper;

import com.example.yourproject.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {
    // 自定义SQL方法(可选)
}

5. 创建Mapper XML文件(可选)

如果需要自定义SQL语句,可以在src/main/resources/mapper目录下创建对应的Mapper XML文件。

例如,UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.yourproject.mapper.UserMapper">
    <!-- 自定义SQL语句 -->
</mapper>

6. 创建Service和Controller

创建Service和Controller来调用Mapper接口。

Service:

package com.example.yourproject.service;

import com.example.yourproject.entity.User;
import com.example.yourproject.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

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

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

    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    public void saveUser(User user) {
        userMapper.insert(user);
    }

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

    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }
}

Controller:

package com.example.yourproject.controller;

import com.example.yourproject.entity.User;
import com.example.yourproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

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

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public void saveUser(@RequestBody User user) {
        userService.saveUser(user);
    }

    @PutMapping
    public void updateUser(@RequestBody User user) {
        userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}

7. 启动项目

运行Spring Boot项目,访问对应的接口即可测试MyBatis-Plus的CRUD功能。


8. 配置分页插件(可选)

MyBatis-Plus提供了分页插件,可以在application.yml中配置:

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
  plugins:
    pagination:
      enabled: true

然后在Service中使用分页功能:

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

public Page<User> getUsersByPage(int current, int size) {
    Page<User> page = new Page<>(current, size);
    return userMapper.selectPage(page, null);
}
posted @   软件职业规划  阅读(307)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示