1. 官方网址
2. 基本应用
2.1 Mybatis + MP
2.1.1 导入依赖
<dependencies>
<!-- mybatis-plus插件依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.1.1</version>
</dependency>
<!--Mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency>
<!--简化bean代码的⼯具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
2.1.2 先配置纯Mybatis应用
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/atm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
编写Mybatis主配置文件mybatis-config.xml
<?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"></properties>
<!--environments: 运⾏环境-->
<environments default="development">
<environment id="development">
<!--当前的事务事务管理器是JDBC-->
<transactionManager type="JDBC"></transactionManager>
<!--数据源信息 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 package="mapper"></mapper>
</mappers>
</configuration>
编写实体类User
@Data // getter setter @toString
@NoArgsConstructor // 无参构造
@AllArgsConstructor // 全参构造
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
编写UserMapper接⼝
public interface UserMapper {
List<User> findAll();
}
编写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="com.lagou.mapper.UserMapper">
<!-- 查询所有 -->
<select id="findAll" resultType="com.lagou.pojo.User">
select * from user
</select>
</mapper>
测试
public class MPTest {
@Test
public void test1() 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();
for (User user : all) {
System.out.println(user);
}
}
}
2.1.3 然后配置无侵入使用MP(Mybatis + MP应用)
第⼀步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有⽅法:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lagou.pojo.User;
public interface UserMapper extends BaseMapper<User> {
List<User> findAll();
}
第⼆步,使⽤MP中的MybatisSqlSessionFactoryBuilder进程构建:
@Test
public void test2() 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);
for (User user : all) {
System.out.println(user);
}
// 也可以使用原生的Mybatis手写方法
List<User> all2 = mapper.findAll();
for (User user : all2) {
System.out.println(user);
}
}
2.2 Spring + Mybatis + MP
引入依赖 ```xml
5.1.6.RELEASE
2. 编写jdbc.properties
```properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mp?serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=root
编写Spring主配置文件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"/>
<!--dataSource-->
<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="com.atm.mapper"/>
</bean>
</beans>
编写User对象以及UserMapper接⼝: ```java @Data @NoArgsConstructor @AllArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }
public interface UserMapper extends BaseMapper
5. 编写测试⽤例:
```java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpringMP {
@Autowired
private UserMapper userMapper;
@Test
public void test2() throws IOException {
List<User> users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}
2.3 SpringBoot + MP
导入依赖
<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>
<!--简化代码的⼯具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mybatis-plus的springboot⽀持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
编写application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?
useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=tr
ue&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
编写pojo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
编写mapper
public interface UserMapper extends BaseMapper<User> {
}
编写启动类
package com.atm.mp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@MapperScan("com.atm.mp.mapper") //设置mapper接⼝的扫描包
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
编写测试⽤例
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
List<User> userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
}
3. 通用CRUD
3.1 新增
3.2 修改
3.3 删除
3.4 查询
普通查询
- 分页查询
- 方法定义: ```java /**
- 根据 entity 条件,查询全部记录(并翻⻚) *
- @param page 分⻚查询条件(可以为 RowBounds.DEFAULT)
@param queryWrapper 实体对象封装操作类(可以为 null) */ IPage
selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper); 2. 配置分⻚插件:
```java
package com.atm.mp;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.atm.mapper") //设置mapper接⼝的扫描包
public class MybatisPlusConfig {
/**
* 分⻚插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
- 测试⽤例:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectPage() {
QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 20); //年龄⼤于20岁
Page<User> page = new Page<>(1,1);
//根据条件查询数据
IPage<User> iPage = this.userMapper.selectPage(page, wrapper);
System.out.println("数据总条数:" + iPage.getTotal());
System.out.println("总⻚数:" + iPage.getPages());
List<User> users = iPage.getRecords();
for (User user : users) {
System.out.println("user = " + user);
}
}
}
4. 配置
4.1 基本配置
4.1.1 配置文件configuration
MyBatis 配置⽂件位置,如果有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。
springboot:
spring mvc:mybatis-plus.config-location = classpath:mybatis-config.xml
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
4.1.2 mapper路径mapperLocations
MyBatis Mapper 所对应的 XML ⽂件位置,如果您在 Mapper 中有⾃定义⽅法(XML 中有⾃定义实
现),需要进⾏该配置,告诉 Mapper 所对应的 XML ⽂件位置。
springboot:
spring mvc:mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
>
<property name="mapperLocations" value="classpath*:mybatis/*.xml"/>
</bean>
4.1.3 类别名typeAliasesPackage
MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML ⽂件
中可以直接使⽤类名,⽽不⽤使⽤全限定的类名(即 XML 中调⽤的时候不⽤包含包名)。
springboot:
spring mvc:mybatis-plus.type-aliases-package = com.atm.mp.pojo
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
>
<property name="typeAliasesPackage"
value="com.baomidou.mybatisplus.samples.quickstart.entity"/>
</bean>
4.2 进阶配置
4.2.1 驼峰转换mapUnderscoreToCamelCase
- 类型:boolean
- 默认值:true
是否开启⾃动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到
经典 Java 属性名 aColumn(驼峰命名) 的类似映射。
#关闭⾃动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
mybatis-plus.configuration.map-underscore-to-camel-case=false
4.2.2 cacheEnabled
- 类型:boolean
- 默认值:true
全局地开启或关闭配置⽂件中的所有映射器已经配置的任何缓存,默认为 true。
mybatis-plus.configuration.cache-enabled=false
4.3 DB配置
4.3.1 idType
- 类型:com.baomidou.mybatisplus.annotation.IdType
- 默认值:ID_WORKER
全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。
springboot:
mybatis-plus.global-config.db-config.id-type=auto
springmvc:
<!--这⾥使⽤MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
>
<property name="dataSource" ref="dataSource"/>
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean
class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="idType" value="AUTO"/>
</bean>
</property>
</bean>
</property>
</bean>
4.3.2 tablePrefix
- 类型:string
- 默认值: null
表名前缀,全局配置后可省略@TableName()配置。
springboot:
mybatis-plus.global-config.db-config.table-prefix=tb_
spring mvc:
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
>
<property name="dataSource" ref="dataSource"/>
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean
class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="idType" value="AUTO"/>
<property name="tablePrefix" value="tb_"/>
</bean>
</property>
</bean>
</property>
</bean>
5. 条件构造器
- 等式
- eq:等于
- ne:不等于
- gt:大于
- ge:大于等于
- lt:小于
- le:小于等于
- between 值1 and 值2
- not between 值1 and 值2
- in:字段 in(value1,value2)
- notIn:字段 not in(value1,value2)
- 模式查询
- like:LIKE ‘%值%’
- notLike:NOT LIKE ‘%值%’
- likeLeft:LIKE ‘%值’
- likeRight:LIKE ‘值%’
- 排序
- orderBy
- orderByAsc
- orderByDesc
- 逻辑查询