Mybatis-plus

# Mybatis-plus

苞米豆点com

https://baomidou.com/
1

# 创建数据库和添加数据

  • 创建数据库

    CREATE DATABASE `mybatis_plus_demo` CHARACTER SET utf8mb4;
    
    1
  • 选择该数据库

    use `mybatis_plus_demo`
    
    1
  • 创建数据表user

    DROP TABLE IF EXISTS user;
    
    CREATE TABLE user
    (
    	id BIGINT(20) NOT NULL 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)
    );
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
  • 插入测试数据

    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');
    
    1
    2
    3
    4
    5
    6
    7
    8

# 创建项目工程

  • 引入父工程

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/>
    </parent>
    
    1
    2
    3
    4
    5
    6
  • 添加相关的依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
             <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
  • 配置文件

    spring:
      application:
        name: mybatis-demo
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://192.168.220.128:3306/mybatis_plus_demo?characterEncoding=utf-8&useSSL=false&useUnicode=true
        username: root
        password: 123456
    
    1
    2
    3
    4
    5
    6
    7
    8

    mysql6以上的需要配置时区

    JavaWeb数据库Mysql驱动配置小记 (opens new window)

# 测试代码

@SpringBootTest
public class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 增删改查测试

/***
* 查询所有
*/
@Test
public void testSelect() {
    System.out.println(("----- selectAll method test ------"));
    List<User> userList = userMapper.selectList(null);
    System.out.println("userList.size() ==> " + userList.size());
    userList.forEach(System.out::println);
}


/**
 * 根据ID来查询
*/
@Test
public void testSelectById() {
    //第一种写法
    // User user = userMapper.selectById(1);
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    //封装条件
    queryWrapper.eq("id", 1);
    queryWrapper.select("name", "email");
    User user = userMapper.selectOne(queryWrapper);
    System.out.println("user==> " + user);
}


/**
* 条件查询
*/
@Test
public void testQueryWrapper() {
    //名字带J的查询出来
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.like("name", "%o%");
    List<User> items = userMapper.selectList(queryWrapper);
    for (User item : items) {
        System.out.println("item ==> " + item);
    }
}

/**
* 插入数据
*/
@Test
public void testInsertData() {
    User user = new User();
    //封装数据
    user.setAge(30);
    user.setEmail("test@sob.com");
    user.setName("测试deleted");
    user.setCreateTime(new Date());
    user.setUpdateTime(new Date());
    userMapper.insert(user);
}


/***
* 测试更新数据
*/
@Test
public void testUpdateData() {
    //根据ID来更新
    User user = new User();
    user.setId(1432730403449401345L);
    //设置修改的数据
    user.setName("测试更新");
    userMapper.updateById(user);
    //根据条件来更新数据
    User targetUser = new User();
    //封装数据
    targetUser.setEmail("newEmail@Test.com");
    //更新条件
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    //封装条件
    queryWrapper.eq("name", "Billie");
    userMapper.update(targetUser, queryWrapper);
}

/**
* 删除数据by ID
*/
@Test
public void testDeleteDataById() {
    //        User user = new User();
    //        user.setId(1L);
    //        userMapper.deleteById(user);
    userMapper.deleteById(1432741920752312322L);
}

/**
 * 根据条件删除数据
 */
@Test
public void testDeleteData() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("email", "test@sob.com");
    int delete = userMapper.delete(queryWrapper);
    System.out.println("delete ==> " + delete);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102

# 自动填充

字段添加注解

@Data
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    private Integer age;
    private String email;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT)
    private String deleted;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

配置插入内容

@Component
public class MBMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "deleted", String.class, "0");
        System.out.println("insertFill...");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        System.out.println("updateFill...");
    }
    
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 逻辑删除配置

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 输出Sql语句执行日志
  global-config:
    db-config:
      logic-delete-field: deleted  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
1
2
3
4
5
6
7
8

字段添加注解,也可以不加,为了更好的阅读性,可以添加

@Data
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    private Integer age;
    private String email;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT)
    @TableLogic
    private String deleted;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 分页查询

配置分页插件

@Configuration
public class MybatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }

}
1
2
3
4
5
6
7
8
9
10
11

分页查询代码

 /**
 * 分页查询
 */
@Test
public void testListByPage() {
    //传过来的参数一般有:
    //page页码,一般从1开始
    //size每页的内容数量
    //条件
    int page = 1;
    int size = 2;
    Page<User> requestPage = new Page<>(page - 1, size);
    Page<User> resultPage = userMapper.selectPage(requestPage, null);
    List<User> records = requestPage.getRecords();
    for (User record : records) {
        System.out.println("item ==> " + record);
    }
    long resultSize = resultPage.getSize();
    long resultTotal = resultPage.getTotal();
    long resultCurrent = requestPage.getCurrent();
    long pages = requestPage.getPages();
    System.out.println("每页数量:" + resultSize);
    System.out.println("总数:" + resultTotal);
    System.out.println("当前页页码:" + resultCurrent);
    System.out.println("pages:" + pages);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 代码生成器

public class GeneratorCodes {

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir("D:/demo/mybatis_plus_demo/src/main/java");
        gc.setAuthor("sob");
        gc.setOpen(false);//生成以后是否打开文件夹
        gc.setSwagger2(true);//实体属性 Swagger2 注解
        gc.setFileOverride(true);//true表示覆盖原来的
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://192.168.220.128:3306/mybatis_plus_demo?characterEncoding=utf-8&useSSL=false&useUnicode=true");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("ucenter");
        pc.setParent("net.sunofbeach");
        pc.setController("api");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setEntity("pojo");
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //多个表的时候,写多个就可以
        strategy.setInclude("user");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.execute();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

swagger2 依赖

<!-- RESTful APIs swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11

spring mvc的依赖

<!--web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
1
2
3
4
5

让maven构建的时候,把xml也输出到target上

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>
1
2
3
4
5
6
7
8
9
10
11

参考配置

spring:
  application:
    name: mybatis-plus-demo
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.220.128:3306/mybatis_plus_demo?characterEncoding=utf-8&useSSL=false&useUnicode=true
    username: root
    password: 123456
server:
  port: 9090
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 输出Sql语句执行日志
  global-config:
    db-config:
      logic-delete-field: deleted  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
  mapper-locations: classpath:net/sunofbeach/ucenter/mapper/xml/*xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

到此,我们就大概练习了一下增删改查,接下来的实践,我们就从做项目开始吧。

上次更新: 2022/03/28, 23:04:38