Spring Boot - 简单地使用 MyBatis-Plus

环境

操作系统:

Windows 10 x64

集成开发环境:

Spring Tool Suite 4 
Version: 4.14.0.RELEASE
Build Id: 202203131612

MySQL 数据库:

mysql> status
--------------
mysql  Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using  EditLine wrapper

Server version:         5.7.30 MySQL Community Server (GPL)

准备

数据库表结构:

mysql> describe user;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | bigint(20)  | NO   | PRI | NULL    | auto_increment |
| username | varchar(10) | NO   |     | NULL    |                |
| password | varchar(10) | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

建表语句:

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(10) NOT NULL,
  `password` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

使用 MyBatis-Plus

初始化工程

新建 Spring Starter Project:

在这里插入图片描述

引入 MySQL DriverLombok 等依赖:

在这里插入图片描述

项目结构

在这里插入图片描述

添加依赖

pom.xml 配置文件中,引入 MyBatis-Plus 依赖(第 30 ~ 34 行):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    
    <groupId>com.mk</groupId>
    <artifactId>Spring-Boot-MyBatis-Plus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-MyBatis-Plus</name>
    <description>Demo project for Spring Boot</description>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

配置

application.yml 配置文件中,添加数据库的相关配置:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.88.158:3306/account?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=true
    username: root
    password: 123456

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 mapper 包(第 8 行):

package com.mk;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.mk.mapper")
public class SpringBootMyBatisPlusApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMyBatisPlusApplication.class, args);
    }
}

编码

提示:此处的实体类、服务类接口及其实现类是由 MyBatis-Plus 提供的代码生成器生成的。

编写实体类 User

package com.mk.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * @author mk
 * @since 2022-03-21
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    private String username;

    private String password;

    @Override
    public Serializable pkVal() {
        return this.id;
    }
}

编写 mapper 接口 UserMapper

package com.mk.mapper;

import com.mk.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * @author mk
 * @since 2022-03-21
 */
public interface UserMapper extends BaseMapper<User> {

}

编写服务类接口 UserService 及其实现类 UserServiceImpl

package com.mk.service;

import com.mk.pojo.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * @author mk
 * @since 2022-03-21
 */
public interface UserService extends IService<User> {

}
package com.mk.service.impl;

import com.mk.pojo.User;
import com.mk.mapper.UserMapper;
import com.mk.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * @author mk
 * @since 2022-03-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

开始使用

添加测试类,进行功能测试:

package com.mk;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.mk.mapper.UserMapper;
import com.mk.pojo.User;
import com.mk.service.UserService;

@SpringBootTest
class SpringBootMyBatisPlusApplicationTests {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserService userService;
    
    
    @Test
    void contextLoads() {
    }
    
    @Test
    void testInsert() {
        {
            User user = new User();
            user.setUsername("wangwu");
            user.setPassword("123");
            
            userMapper.insert(user);
        }
        
        {
            User user = new User();
            user.setUsername("zhangliu");
            user.setPassword("123");
            
            userService.save(user);
        }
    }
    
    @Test
    void testSelect() {
        List<User> users = userMapper.selectList(null);
        
        System.out.println(users);
    }
}

查看结果

执行以上测试类之后,可以在 MySQL 数据库中看到:

mysql> select * from user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | zhangsan | 123      |
|  2 | lisi     | 123      |
|  3 | wangwu   | 123      |
|  4 | zhangliu | 123      |
+----+----------+----------+
4 rows in set (0.00 sec)

参考

MyBatis-Plus > 快速入门 > 快速开始

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值