一、简介
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生(官网)。
二、一个简单的实例
SpringBoot+MyBatis-Plus 实现通过 ID 查找数据。
Maven 依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok 用于简化代码-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--引入阿里数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!--整合Spring-boot-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
<!--SpringBoot的单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
Spring 配置文件
spring:
# 配置数据源
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shiro?serverTimezone=GMT%2B8&useSSL=false&serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@TableName("tb_user")
public class User {
@TableId("user_id")
private int id;
@NonNull
@TableField("user_name")
private String name;
@NonNull
@TableField("user_password")
private String password;
@NonNull
@TableField("user_grade")
private int grade;
}
mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
启动类
@MapperScan("top.zyxwmj.mybatis.mapper")
@SpringBootApplication
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo {
@Resource
private UserMapper userMapper;
@Test
public void test(){
System.out.println(userMapper.selectById(1));
}
}
三、MyBatis-Plus 的常用操作
1、@TableName、@TableId 、@TableField 的用法
@TableName:表名注解,用于 bean 上其 value 值指向对应的数据表。
@TableId:主键注解,用于 bean 的成员变量上其 value 值指向对应的数据表的主键;type 值表示主键的类型(默认:IdType.NONE)。
@TableField:字段注解,用于 bean 的成员变量上其 value 值指向对应的数据表的字段;select 属性的值为 false 时候表示查询时不返回该字段的值;exist 属性的值为 false 时表示在数据表中没有该字段。
2、BaseMapper 的用法
实现 BaseMapper 接口后提供基本的 CRUD 的方法。
1)添加数据
int insert(T entity);
2)删除数据
① 根据 ID 删除数据
int deleteById(Serializable id);
② 多 and 条件删除数据
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
例如:
Map<String,Object> map=new HashMap<>();
map.put("user_name","Yi-Xing");
map.put("user_password","1234");
// 根据 map 删除数据,多条件之间是 and 关系
userMapper.deleteByMap(map);
③ 根据条件删除数据
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
例如:
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.eq("user_name","Yi-Xing");
userMapper.delete(wrapper);
④ 根据 ID 批量删除数据
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
例如:
userMapper.deleteBatchIds(Arrays.asList(3,4));
3)更新数据
① 根据 ID 更新数据
int updateById(@Param(Constants.ENTITY) T entity);
② 根据条件更新所有数据
设置指定条件,更新所有字段。
User user=new User("Yi-Xing","123");
QueryWrapper<User> wrapper=new QueryWrapper<>();
// 设置匹配条件等于 user_name=Yi-Xing1
wrapper.eq("user_name","Yi-Xing1");
int result=userMapper.update(user,wrapper);
③ 根据条件更新指定数据
只更新 user_name 和 user_password 字段的信息。
UpdateWrapper<User> wrapper=new UpdateWrapper<>();
wrapper.set("user_name","zyxwmj.top")
.set("user_password","1234")
.eq("user_name","Yi-Xing");
int result=userMapper.update(null,wrapper);
4)查询数据
① 根据 ID 查询数据
T selectById(Serializable id);
② 根据 ID 批量查询数据
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
例如:
userMapper.selectBatchIds(Arrays.asList(1,2));
③ 查询单条数据
如果查询到的数据量大于 1,则抛异常。
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
④ 统计查询总数量
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
⑤ 根据条件查询指定数据
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
⑥ 分页查询
使用分页前先进行一下配置。
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
执行分页查询。
<E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
例如:
// 第一页,每页两条数据
Page<User> page=new Page<>(1,2);
QueryWrapper<User> wrapper=new QueryWrapper<>();
// 设置查询条件
wrapper.like("user_name","1");
IPage<User> iPage=userMapper.selectPage(page,wrapper);
System.out.println("总个数"+iPage.getTotal());
System.out.println("总页数"+iPage.getPages());
System.out.println("当前页"+iPage.getCurrent());
System.out.println("当前页的数据"+iPage.getRecords());
四、条件构造器
QueryWrapper 和 UpdateWrapper 的父类用于生成 SQL 的 where 条件,entity 属性也用于生成 SQL 的 where 条件。注意:entity 生成的 where 条件与使用各个 API 生成的 where 条件没有任何关联行为。
常用方法
方法名 | 解释 | 方法名 | 解释 |
---|---|---|---|
eq | = | ne | <> |
gt | > | ge | >= |
lt | < | le | <= |
between | BETWEEN 值 1 AND 值 2 | notBetween | NOT BETWEEN 值 1 AND 值 2 |
in | IN(1,2...) | netIn | NOT IN(1,2...) |
like | LIKE '% 值 %' | notlike | NOT LIKE '% 值 %' |
likeLeft | LIKE '% 值' | likeRight | LIKE '值 %' |
orderBy | 升降序混合 | orderByAsc | 升序排序 |
orderDesc | 降序混合 | or | 拼接 OR |
and | 拼接 AND | select | 设置查找字段 |
例子:
相当于 SQL:SELECT user_id AS id,user_name AS name FROM tb_user WHERE (user_name LIKE ? OR user_grade >= ?) ORDER BY user_grade ASC
QueryWrapper<User> wrapper=new QueryWrapper<>();
// 设置查询条件
wrapper.like("user_name","1")
.or()
.ge("user_grade",2)
.orderBy(true,true,"user_grade")
.select("user_id AS id","user_name AS name");
System.out.println(wrapper.lambda().getSqlSelect());
List<User> list=userMapper.selectList(wrapper);
五、MyBatis-Plus 的配置
在 MP 中有大量的配置,其中有一部分是 MyBatis 原生的配置,另一部分是 MP 的配置。
例如:在 MyBatis-Plus 的配置文件中配置分页插件
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//ED"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"/>
</plugins>
</configuration>
1、configLocation
MyBatis 配置文件位置,如果你有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。
mybatis-plus:
# 配置Mybatis-Plus配置文件位置
config-location: classpath:mybatis-config.xml
# configuration: 不能和该配置一起出现否则报错
2、mapperLocations
MyBatis Mapper 所对应的 XML 文件位置,如果你在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
mybatis-plus:
mapper-locations: classpath*:mybatis/*.xml
3、typeAliasesPackage
MyBatis 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后再 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含全名)。
mybatis-plus:
type-aliases-package: top.zyxwmj.mybatis.bean
4、mapUnderscoreToCamelCase
是否开启自动驼峰命名规则映射,即从经典数据库列名 A_COLUMN(下划线命名)到经典 Java 属性名 aColumn(驼峰命名)的类似映射,在 MyBatis 默认为 false,在 MyBatis-Plus 默认为 true。
5、cacheEnabled
全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true。
6、idType
全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。
7、tablePrefix
表名前缀,全局配置后可省略@TableName()配置。
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
global-config:
db-config:
id-type: auto
table-prefix: tb_
六、MyBatis-Plus 的更多功能
标题:SpringBoot 整合 MyBatis-Plus
作者:Yi-Xing
地址:http://47.94.239.232:10014/articles/2020/01/13/1578885714782.html
博客中若有不恰当的地方,请您一定要告诉我。前路崎岖,望我们可以互相帮助,并肩前行!