SpringBoot整合MyBatis-Plus操作MySQL数据

警告
本文最后更新于 2023-03-01,文中内容可能已过时,请谨慎使用。
所用版本
  • SpringBoot: 2.7.9

  • mysql: 8.0.32

  • Spring Boot Starter JDBC
  • Project Lombok
  • MySQL Connector/J
  • mybatis-plus-boot-starter
  • mybatis-plus-generator

maven仓库地址:https://mvnrepository.com/

下面安装都是最新版,在pom.xml中添加下面依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    <version>3.0.3</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.26</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.32</version>
</dependency>

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

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.3.1</version>
</dependency>

application.properties添加下列配置

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

如果使用的是yml配置文件,可添加如下配置

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

注意修改自己的用户名和密码,mysql服务器主机地址和端口,连接的数据库名称

以一张简单用户表(user)为例

建表和插入数据

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id INT(20) AUTO_INCREMENT COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

SpringBoot中的常用模块

  • pojo层 (也叫Entity层):将数据库中的表对应成Java中的Class
  • mapper层(也叫Dao层):将pojo层的class中的操作,映射成sql语句
  • service层:写具体的业务逻辑,组合使用mapper中的操作
  • controller层:负责请求转发,接受页面过来的参数,传给Service处理,接到返回值,再传给页面

文件结构:

com
   +- APP
         +- Application.java  
         |
         +- pojo
         |   +- User.java
         +- mapper
         |   +- UserMapper.java
         +- controller
             +- UserController.java
         +- Service
             ...

pojo层:建立对应的User

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String email;
}

mapper层:建立一个UserMapper

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

controller层: 建立一个userController类来设计接口,测试增删改查等基本功能

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;


    /**
     * url: http://localhost:8080/user/all/
     * @return 所有用户数据
     */
    @GetMapping("/user/all/")
    public List<User> getAll() {
        return userMapper.selectList(null);
    }


    /**
     * url: http://localhost:8080/user/1/
     * @param userId 用户id
     * @return 用户信息
     */
    @GetMapping("/user/{userId}/")
    public User getUser(@PathVariable int userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);

        return userMapper.selectOne(queryWrapper);
    }

    /**
     * url: http://localhost:8080/user/1/?name=aaa
     * @param userId 用户id
     * @param name 修改后的name
     * @return "Update Name Successful"
     */
    @PutMapping("/user/{userId}/")
    public String updateUserName(@PathVariable int userId,
                                 @RequestParam String name) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        // 修改name
        updateWrapper.set("name", name);
        // 条件: 更新指定id的用户信息
        updateWrapper.eq("id", userId);

        userMapper.update(new User(), updateWrapper);
        return "Update Name Successful";
    }

    /**
     * url: http://localhost:8080/user/1/3/
     * @param lowId  查询的id下限
     * @param highId 查询的id上限
     * @return 范围查询的用户信息
     */
    @GetMapping("/user/{lowId}/{highId}/")
    public List<User> getRangeUser(@PathVariable int lowId,
                                   @PathVariable int highId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("id", lowId).le("id", highId);
        return userMapper.selectList(queryWrapper);
    }


    /**
     * url: http://localhost:8080/user/add/10/bbb/18/test@email.com/
     * @param userId   用户id
     * @param username 用户名
     * @param age 年龄
     * @param email 邮箱
     * @return "Add User Successful"
     */
    @PostMapping("/user/add/{userId}/{username}/{age}/{email}/")
    public String addUser(@PathVariable int userId,
                          @PathVariable String username,
                          @PathVariable int age,
                          @PathVariable String email) {

        User user = new User(userId, username, age, email);
        userMapper.insert(user);
        return "Add User Successful";
    }

    /**
     * url: http://localhost:8080/user/delete/1/ 
     * 根据用户id删除某个用户
     * @param userId 用户id
     * @return "Delete User Successful"
     */
    @DeleteMapping("/user/delete/{userId}/")
    public String deleteUser(@PathVariable int userId) {
        userMapper.deleteById(userId);
        return "Delete User Successful";
    }
}

相关文章