跳转至

Mybatis Plus#

约 178 个字 41 行代码 预计阅读时间 5 分钟

入门案例#

创建项目,导入相关依赖:

XML
<?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>3.3.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.luguosong</groupId>
    <artifactId>mybatis-plus-hello</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis-plus-hello</name>
    <description>mybatis-plus-hello</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--MyBatis-Plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml文件配置数据库连接:

YAML
spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/programming_notes
    username: root
    password: 12345678
  sql:
    init:
      schema-locations: classpath:db/schema.sql
      data-locations: classpath:db/data.sql
      mode: always

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

Java
package com.luguosong.mybatisplushello;

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

@SpringBootApplication
@MapperScan("com.luguosong.mybatisplushello.mapper")
public class MybatisPlusHelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusHelloApplication.class, args);
    }

}

编写实体类:

Java
package com.luguosong.mybatisplushello.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

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

编写 Mapper 接口类:

Java
package com.luguosong.mybatisplushello.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.luguosong.mybatisplushello.entity.User;

/**
 * @author luguosong
 */
public interface UserMapper extends BaseMapper<User> {

}

编写测试类:

Java
package com.luguosong.mybatisplushello;

import com.luguosong.mybatisplushello.entity.User;
import com.luguosong.mybatisplushello.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MybatisPlusHelloApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void testSelect() {
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

}

常见注解#

@TableName#

默认情况实体类类名驼峰转下划线作为表名,@TableName用来自定义表名。

Java
@TableName("tb_user")
public class User {

    private Long id;

    private String name;
}

@TableId#

默认情况下实体类名为id的字段作为主键,@TableId用来自定义主键。

Java
public class User {

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

    private String name;
}

@TableField#

默认情况下实体类成员字段名驼峰转下划线作为表的字段名,@TableField用来自定义字段名。

Java
@TableName("tb_user")
public class User {

    private Long id;

    // 实体类字段名与表字段不一致,可以使用@TableField注解指定表字段名
    @TableField("user_name")
    private String name;

    //当表字段名与mysql关键字冲突,可以使用转义字符处理
    @TableField("`order`")
    private String order;

    // 当实体类字段在表中不存在时
    @TableField(exist = false)
    private String address;
}

条件构造器#

详细条件构造器参考官网

WrapperTest.java
package com.luguosong.mybatisplushello;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.luguosong.mybatisplushello.entity.User;
import com.luguosong.mybatisplushello.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author luguosong
 */
@SpringBootTest
public class WrapperTest {
    @Autowired
    private UserMapper userMapper;

    /*
     * 条件查询
     * */
    @Test
    void testSelect() {
        /*
         * 构造条件
         * */
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("name", "age"); //查询指定字段
        wrapper.like("name", "o");
        wrapper.ge("age", 20);

        /*
         * 查询
         * */
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }

    /*
     * 条件更新
     * */
    @Test
    void testUpdate() {
        //构造更新条件
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.setSql("age=10");
        wrapper.in("id", List.of(1, 2, 3));

        //更新数据
        userMapper.update(null, wrapper);
    }

    /*
     * 使用Lambda构造条件
     * 👍🏻推荐使用,防止硬编码
     * */
    @Test
    void testLambdaSelect() {
        /*
         * 构造条件
         * */
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User::getName, User::getAge); //查询指定字段
        wrapper.like(User::getName, "o");
        wrapper.ge(User::getAge, 20);

        /*
         * 查询
         * */
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }
}

自定义SQL#

Service接口#

评论