MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
名称 | 地址 |
---|---|
官网 | https://baomidou.com/ |
Github | https://github.com/baomidou/mybatis-plus |
Gitee | https://gitee.com/baomidou/mybatis-plus |
文档发布地址 | https://baomidou.com/pages/24112f |
CREATE DATABASE `mybatis_plus` ;
use `mybatis_plus`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
<parent>
<artifactId>spring-boot-starter-parentartifactId>
<groupId>org.springframework.bootgroupId>
<version>2.3.5.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.3.1version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.79version>
dependency>
dependencies>
spring:
# 配置数据源信息
datasource:
# 配置连接数据库信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true
username: root
password: root
在Spring Boot启动类中添加@MapperScan注解,扫描mapper包
@SpringBootApplication
@MapperScan("com.au.sss.mapper")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class,args);
}
}
@Data
@TableName(value = "user")
public class UserEntity {
private Long id;
private String name;
private Integer age;
private String email;
}
BaseMapper是MyBatis-Plus提供的模板mapper,其中包含了基本的CRUD方法,泛型为操作的实体类型
public interface UserMapper extends BaseMapper<UserEntity> {
}
@RestController
public class UserController {
@Resource
private UserMapper userMapper;
@GetMapping("/selectList")
public String selectList(){
List<UserEntity> list = userMapper.selectList(null);
return JSON.toJSONString(list);
}
}
在application.yml中配置日志输出
# 配置MyBatis日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
MyBatis-Plus中的基本CRUD在内置的BaseMapper中都已得到了实现,我们可以直接使用,接口如下:
说明:
- 通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
- 泛型 T 为任意实体对象
- 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承
Mybatis-Plus 提供的基类
创建Service接口集成IService
/**
* UserService继承IService模板提供的基础功能
*/
public interface UserService extends IService<UserEntity> {
}
创建Service接口实现类
/**
* ServiceImpl实现了IService,提供了IService中基础功能的实现
* 若ServiceImpl无法满足业务需求,则可以使用自定的UserService定义方法,并在实现类中实现
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
}
测试调用service进行数据库操作
@Resource
private UserService userService;
@GetMapping("/selectAll")
public int selectAll(){
return userService.count();
}
说明:
QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件
注意: entity 生成的 where 条件与 使用各个 api 生成的 where 条件没有任何关联行为
全部eq(或个别isNull)
例1: allEq({id:1,name:“老王”,age:null})—>id = 1 and name = ‘老王’ and age is null
例2: allEq({id:1,name:“老王”,age:null}, false)—>id = 1 and name = ‘老王’
等于 =
例: eq(“name”, “老王”)—>name = ‘老王’
不等于 <>
例: ne(“name”, “老王”)—>name <> ‘老王’
大于 >
例: gt(“age”, 18)—>age > 18
小于 <
例: lt(“age”, 18)—>age < 18
小于等于 <=
例: le(“age”, 18)—>age <= 18
BETWEEN 值1 AND 值2
例: between(“age”, 18, 30)—>age between 18 and 30
NOT BETWEEN 值1 AND 值2
例: notBetween(“age”, 18, 30)—>age not between 18 and 30
LIKE ‘%值%’
例: like(“name”, “王”)—>name like ‘%王%’
NOT LIKE ‘%值%’
例: notLike(“name”, “王”)—>name not like ‘%王%’
LIKE ‘%值’
例: likeLeft(“name”, “王”)—>name like ‘%王’
LIKE ‘值%’
例: likeRight(“name”, “王”)—>name like ‘王%’
NOT LIKE ‘%值’
例: notLikeLeft(“name”, “王”)—>name not like ‘%王’
NOT LIKE ‘值%’
例: notLikeRight(“name”, “王”)—>name not like ‘王%’
字段 IS NULL
例: isNull(“name”)—>name is null
字段 IS NOT NULL
例: isNotNull(“name”)—>name is not null
字段 IN (value.get(0), value.get(1), …)
例: in(“age”,{1,2,3})—>age in (1,2,3)
字段 NOT IN (value.get(0), value.get(1), …)
例: notIn(“age”,{1,2,3})—>age not in (1,2,3)
字段 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)
字段 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)
分组:GROUP BY 字段, …
例: groupBy(“id”, “name”)—>group by id,name
排序:ORDER BY 字段, … ASC
例: orderByAsc(“id”, “name”)—>order by id ASC,name ASC
排序:ORDER BY 字段, … DESC
例: orderByDesc(“id”, “name”)—>order by id DESC,name DESC
排序:ORDER BY 字段, …
例: orderBy(true, true, “id”, “name”)—>order by id ASC,name ASC
HAVING ( sql语句 )
例: having(“sum(age) > 10”)—>having sum(age) > 10
例: having(“sum(age) > {0}”, 11)—>having sum(age) > 11
拼接 OR
注意事项:主动调用or表示紧接着下一个方法不是用and连接!(不调用or则默认为使用and连接)
例: eq(“id”,1).or().eq(“name”,“老王”)—>id = 1 or name = ‘老王’
AND 嵌套
例: and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”))—>and (name = ‘李白’ and status <> ‘活着’)
无视优化规则直接拼接到 sql 的最后
last(“limit 1”)
拼接 EXISTS ( sql语句 )
例: exists(“select id from table where age = 1”)—>exists (select id from table where age = 1)
说明:
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件
及 LambdaQueryWrapper, 可以通过 new QueryWrapper().lambda() 方法获取
设置查询字段
说明:
以上方法分为两类.
第二类方法为:过滤查询字段(主键除外),入参不包含 class 的调用前需要wrapper内的entity属性有值! 这两类方法重复调用以最后一次为准
例: select(“id”, “name”, “age”)
例: select(i -> i.getProperty().startsWith(“test”))
说明:
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件
及 LambdaUpdateWrapper, 可以通过 new UpdateWrapper().lambda() 方法获取!
SQL SET 字段
例: set(“name”, “老李头”)
例: set(“name”, “”)—>数据库字段值变为空字符串
例: set(“name”, null)—>数据库字段值变为null
设置 SET 部分 SQL
例: setSql(“name = ‘老李头’”)
链式调用lambda式
// 区分:
// 链式调用 普通
UpdateChainWrapper<T> update();
// 链式调用 lambda 式。注意:不支持 Kotlin
LambdaUpdateChainWrapper<T> lambdaUpdate();
// 等价示例:
query().eq("id", value).one();
lambdaQuery().eq(Entity::getId, value).one();
// 等价示例:
update().eq("id", value).remove();
lambdaUpdate().eq(Entity::getId, value).remove();