MyBaits Plus快速入门
# MyBatis Plus快速入门
参考:快速开始 (opens new window) & 安装 (opens new window)
# 安装
MyBatis-Plus 3.x 版本基于JDK8,提供了lambda形式的调⽤,安装集成要求:
- JDK 8+
- Maven or Gradle
# Release版本
# Spring Boot
Maven:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
Gradle:
compile group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '最新版本'
# Spring
Maven:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>最新版本</version>
</dependency>
Gradle:
compile group: 'com.baomidou', name: 'mybatis-plus', version: '最新版本'
注意
引入 MyBatis-Plus
之后请不要再次引入 MyBatis
以及 MyBatis-Spring
,以避免因版本差异导致的问题。
# 创建数据库以及表
使用MySQL,创建数据库mybatis_plus & 创建User表:
create database mybatis_plus;
use mybatis_plus;
-- 创建测试表
CREATE TABLE IF NOT EXISTS 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)
);
-- 插⼊测试数据
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');
# 快速开始
MyBatis整合MP常常有三种⽤法,分别是MyBatis+MP、Spring+Mybatis+MP、SpringBoot+Mybatis+MP。
这里的Demo工程,MP版本选择较新的v3.4.3 (opens new window)为例,创建Maven的POM工程 hello-mybatis-plus
,引入Maven依赖管理:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>hello-mybatis-plus</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--MyBatis-Plus-Springboot-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<!--MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency>
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-reload4j</artifactId>
<version>2.0.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
# MyBatis + MP
通过纯Mybatis与Mybatis-Plus整合:
- 创建⼦工程Module:mybatis-plus-simple
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.example</groupId>
<artifactId>hello-mybatis-plus</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>mybatis-plus-simple</artifactId>
</project>
父工程定义模块:
<modules>
<module>mybatis-plus-simple</module>
</modules>
log4j.properties:
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
- MyBatis实现查询User
Step1:编写 mybatis-config.xml
⽂件&jdbc.properties
⽂件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<!--environments: 运⾏环境-->
<environments default="development">
<environment id="development">
<!-- 当前的事务事务管理器是JDBC -->
<transactionManager type="JDBC"/>
<!-- 数据源信息 POOLED:使⽤mybatis的连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 引⼊映射配置⽂件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
jdbc.properties
⽂件:
jdbc.driver=com.mysql.cj.jdbc.Driver
#jdbc.driver=com.mysql.jdbc.Driver 5.x 驱动
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
Step2:编写实体User(lombok简化)
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
Step3:编写 UserMapper
接⼝
public interface UserMapper {
List<User> findAll();
}
Step4:编写 UserMapper.xml
⽂件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.hello.mp.mapper.UserMapper">
<select id="findAll" resultType="org.example.hello.mp.entity.User">
select * from user
</select>
</mapper>
Step5:编写 UserMapperTest
测试⽤例:
public class UserMapperTest {
@Test
public void testFindAll() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
all.forEach(System.out::println);
}
}
// 测试结果
// User(id=1, name=Jone, age=18, email=test1@baomidou.com)
// User(id=2, name=Jack, age=20, email=test2@baomidou.com)
// User(id=3, name=Tom, age=28, email=test3@baomidou.com)
// User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
// User(id=5, name=Billie, age=24, email=test5@baomidou.com)
- Mybatis+MP实现查询User
Step1:在引入了MP后,只需要将UserMapper继承 BaseMapper
,就可以拥有MP封装好的CURD方法:
package org.example.hello.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.example.hello.mp.entity.User;
import java.util.List;
public interface UserMapper extends BaseMapper<User> {
List<User> findAll();
}
Step2:使⽤MP中的 MybatisSqlSessionFactoryBuilder构建
SqlSessionFactory`:
@Test
public void testFindAllByMP() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
// 使⽤的是MP的MybatisSqlSessionFactoryBuilder
SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// BaseMapper中定义的⽅法
List<User> all = mapper.selectList(null);
all.forEach(System.out::println);
}
注:如果实体类名称和表名称不⼀致,可以在实体类上添加注解 @TableName("指定数据库表名")
由于使⽤了 MybatisSqlSessionFactoryBuilder
进⾏了构建,继承的 BaseMapper
中的⽅法就载⼊到了 SqlSession
的 mappedStatements
中,所以就可以直接使⽤相关的⽅法。
# Spring + MyBatis + MP
引⼊Spring框架,就可以将数据源、构建等⼯作就交给Spring管理。
创建⼦工程Module,mybatis-plus-spring
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.example</groupId> <artifactId>hello-mybatis-plus</artifactId> <version>1.0-SNAPSHOT</version> </parent> <artifactId>mybatis-plus-spring</artifactId> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>5.1.6.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <scope>test</scope> <version>${spring.version}</version> </dependency> </dependencies> </project>
Spring + Mybatis + MP 实现查询User
Step1:编写 jdbc.properties
⽂件和 log4j.properties
文件(略)
Step2:编写 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--引⼊properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--DBSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--使⽤MP提供的sqlSessionFactory,完成spring与mp的整合-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--扫描mapper接⼝,使⽤的依然是mybatis原⽣的扫描器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.example.hello.mp.mapper"/>
</bean>
</beans>
Step3:编写User对象以及UserMapper接⼝(略)
Step4:编写测试⽤例
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserMapperSpringTest {
@Autowired
private UserMapper userMapper;
@Test
public void testFindAllByMP() throws IOException {
List<User> users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}
# SpringBoot + MyBatis + MP
使⽤SpringBoot将进⼀步的简化MP的整合,需要注意的是,由于使⽤SpringBoot需要继承Parent,所以需要重新创建⼯程,并不是创建⼦Module。
- 创建工程:mybatis-plus-springboot,引入依赖:
<?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 http://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.5.6</version>
<relativePath/>
</parent>
<groupId>org.example</groupId>
<artifactId>mybatis-plus-springboot</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--MyBatis-Plus-Springboot-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<!--MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-reload4j</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.20.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- SpringBoot + Mybatis + MP 实现查询User
Step1:编写 log4j.properties
(略)
Step2:编写 application.properties
:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
Step2:编写User对象以及UserMapper接⼝(略)
Step3:编写启动类
@MapperScan("org.example.hello.mp.mapper")
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Step4:编写测试⽤例
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserMapperSpringTest {
@Autowired
private UserMapper userMapper;
@Test
public void testFindAllByMP() throws IOException {
List<User> users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}