MyBatis Plus 是国内人员开发的 MyBatis 增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。它类似于JPA,对通用的 CRUD 方法进行封装,在进行简单的单表操作时,我们不需要再写xml,而是直接调用这些方法即可,使开发更加简单顺畅。
MyBatis Plus 的核心功能有:支持通用的 CRUD、代码生成器 与 条件构造器。
通用 CRUD:定义好 Mapper 接口后,只需要继承 BaseMapper
接口即可获得通用的增删改查功能,无需编写任何接口方法与配置文件.
条件构造器:通过 EntityWrapper
(实体包装类),可以用于拼接 SQL 语句,并且支持排序、分组查询等复杂的 SQL。
代码生成器:支持策略配置与全局配置,比 MyBatis 的代码生成更好用。
正如官方所说,MyBatis Plus 在 MyBatis 的基础上只做增强不做改变,因此其与 Spring Boot 的整合亦非常简单,只需把 MyBatis 的依赖换成 MyBatis Plus 的依赖即可。
1.在pom.xml中加入对应依赖
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plusartifactId>
<version>2.3version>
dependency>
2.在 application.properties 添加配置,打开驼峰到下划线的映射
mybatis-plus.configuration.map-underscore-to-camel-case = true
3.创建用户表
#创建用户表
CREATE TABLE user (
id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键',
name VARCHAR(30) DEFAULT NULL COMMENT '姓名',
age INT(11) DEFAULT NULL COMMENT '年龄',
address_id BIGINT(20) DEFAULT NULL COMMENT '家庭住址id',
create_time DATETIME DEFAULT NULL COMMENT '创建时间'
) ENGINE=INNODB CHARSET=UTF8;
4.新建与 user 表映射的实体类
// @Data 是 Lombok 的注解,是一种 Java 实用工具,会为我们自动生成 set 和 get 方法
@Data
public class User {
private Long id;
private String name;
private Integer age;
private Long addressId;
private Date createTime;
}
5.dao 层中创建 mapper 接口,继承 MyBatis Plus 的 BaseMapper
public interface UserMapper extends BaseMapper<User> {
}
6.启动类添加 @MapperScan 注解,配置需要扫描的 dao 层接口
@MapperScan("org.demo.dao")
@SpringBootApplication
public class MyBatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisPlusDemoApplication.class, args);
}
}
7.编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBatisPlusDemoApplicationTests {
@Resource
private UserMapper userMapper;
@Test
public void select(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
User user = new User();
user.setAge(3);
user.setAddressId(10L);
user.setCreateTime(new Date());
userMapper.insert(user);
System.out.println("用户id为:" + user.id);
User user = new User();
user.setId(1L);
user.setAge(13);
//根据 id 进行更新,没有传值的属性就不会更新
userMapper.updateById(user);
(1). 根据 id 查询:
User user = userMapper.selectById(1L);
(2). 根据条件查询单条:
User user = new User();
user.setId(1L);
//若是数据库中符合传入的条件的记录有多条,那就不能用这个方法,会报错
User user = userMapper.selectOne(user);
(3). 根据条件查询多条:
Map<String,Object> columnMap = new HashMap<>();
// 表中的列名
columnMap.put("age",13);
List<User> users = userMapper.selectByMap(columnMap);
(4). 通过id批量查询:
List<Long> idList = new ArrayList<>();
idList.add(1L);
idList.add(2L);
idList.add(3L);
List<User> users = userMapper.selectBatchIds(idList);
(1). 根据 id 删除:
userMapper.deleteById(1L);
(2). 根据条件删除:
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("age", 18);
userMapper.deleteByMap(columnMap);
(3). 根据id批量删除:
List<Integer> idList = new ArrayList<>();
idList.add(1);
idList.add(2);
userMapper.deleteBatchIds(idList);
1.allEq
全部 eq (或个别 isNull)
allEq({
id:1,name:"老王",age:null}) ---> id = 1 and name = '老王' and age is null
allEq({
id:1,name:"老王",age:null}, false) ---> id = 1 and name = '老王'
2.eq
等于 =
eq("name", "老王") ---> name = '老王'
3.ne
不等于 <>
ne("name", "老王") ---> name <> '老王'
4.gt
大于 >
gt("age", 18) ---> age > 18
5.ge
大于等于 >=
ge("age", 18) ---> age >= 18
6.lt
小于 <
lt("age", 18) ---> age < 18
7.le
小于等于 <=
le("age", 18) ---> age <= 18
8.between
BETWEEN 值1 AND 值2
between("age", 18, 30) ---> age between 18 and 30
9.notBetween
NOT BETWEEN 值1 AND 值2
notBetween("age", 18, 30) ---> age not between 18 and 30
10.like
LIKE ‘%值%’
like("name", "王") ---> name like '%王%'
10.notLike
NOT LIKE ‘%值%’
notLike("name", "王") ---> name not like '%王%'
11.likeLeft
LIKE ‘%值’
likeLeft("name", "王") ---> name like '%王'
12.likeRight
LIKE ‘值%’
likeRight("name", "王") ---> name like '王%'
13.isNull
字段 IS NULL
isNull("name") ---> name is null
14.isNotNull
字段 IS NOT NULL
isNotNull("name") ---> name is not null
15.in
字段 IN (value.get(0), value.get(1), …)
in("age",{
1,2,3}) ---> age in (1,2,3)
字段 IN (v0, v1, …)
in("age", 1, 2, 3) ---> age in (1,2,3)
16.notIn
字段 NOT IN (value.get(0), value.get(1), …)
notIn("age",{
1,2,3}) ---> age not in (1,2,3)
字段 NOT IN (v0, v1, …)
notIn("age", 1, 2, 3) ---> age not in (1,2,3)
17.inSql
字段 IN ( sql语句 )
inSql("age", "1,2,3,4,5,6") ---> age in (1,2,3,4,5,6)
inSql("id", "select id from table where id < 3") ---> id in (select id from table where id < 3)
18.notInSql
字段 NOT IN ( sql语句 )
notInSql("age", "1,2,3,4,5,6") ---> age not in (1,2,3,4,5,6)
notInSql("id", "select id from table where id < 3") ---> id not in (select id from table where id < 3)
19.groupBy
分组:GROUP BY 字段, …
groupBy("id", "name") ---> group by id,name
20.orderByAsc
排序:ORDER BY 字段, … ASC
orderByAsc("id", "name") ---> order by id ASC,name ASC
21.orderByDesc
排序:ORDER BY 字段, … DESC
orderByDesc("id", "name") ---> order by id DESC,name DESC
22.orderBy
排序:ORDER BY 字段, …
orderBy(true, true, "id", "name") ---> order by id ASC,name ASC
23.having
HAVING ( sql语句 )
having("sum(age) > 10") ---> having sum(age) > 10
having("sum(age) > {0}", 11) ---> having sum(age) > 11
24.or
拼接 OR
eq("id",1).or().eq("name","老王") ---> id = 1 or name = '老王'
OR 嵌套
or(i -> i.eq("name", "李白").ne("status", "活着")) ---> or (name = '李白' and status <> '活着')
25.and
AND 嵌套
and(i -> i.eq("name", "李白").ne("status", "活着")) ---> and (name = '李白' and status <> '活着')
26.last
无视优化规则直接拼接到 sql 的最后
注意事项:只能调用一次,多次调用以最后一次为准 有sql注入的风险,谨慎使用
last("limit 1")
27.exists
拼接 EXISTS ( sql语句 )
exists("select id from table where age = 1") ---> exists (select id from table where age = 1)
28.notExists
拼接 NOT EXISTS ( sql语句 )
notExists("select id from table where age = 1") ---> not exists (select id from table where age = 1)
29.自定义SQL
Service.java
mysqlMapper.getAllList(Wrappers.<MysqlData>lambdaQuery().eq(MysqlData::getGroup, 1));
方案一 注解方式 Mapper.java
@Select("select * from mysql_data ${ew.customSqlSegment}")
List<MysqlData> getAllList(@Param(Constants.WRAPPER) Wrapper wrapper);
方案二 XML形式 Mapper.xml
<select id="getAllList" resultType="MysqlData">
SELECT * FROM mysql_data ${
ew.customSqlSegment}
</select>