MyBatis-Plus-(一)MyBatis-Plus快速入门体验

本文最后更新于:February 19, 2022 pm

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。支持任何能使用 MyBatis 进行 CRUD, 并且支持标准 SQL 的数据库。

目录

快速体验

步骤

  1. 正常创建实体类。
  2. 创建mapper接口(dao层),继承 BaseMapper。
  3. 在主启动类上添加mapp扫描:@MapperScan("com.tothefor.mapper")

依赖

创建SpringBoot项目,并导入依赖:

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

然后正常创建实体类。

Dao层

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.tothefor.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tothefor.pojo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

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

}

主启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.tothefor;

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

@MapperScan("com.tothefor.mapper")
@SpringBootApplication
public class MybatisplusDemoApplication {

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

}

测试

1
2
3
4
5
6
7
8
9
10
11
@Autowired
private UserMapper userMapper;

@Test
void contextLoads() {

List<User> users = userMapper.selectList(null);

users.forEach(it -> System.out.println(it));

}

配置日志

1
2
3
4
5
6
7
8
9
10
11
spring:
datasource:
username: root
password: loong461
url: jdbc:mysql://localhost:3306/te?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl