MyBatis-Plus基本操作
依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
基础操作
DAO层
public interface UserMapper extends BaseMapper<User> {
}
注解
@TableName 找到数据库中对应的表
@TableId 表示为主键(type可以设置自增长,默认雪花算法)
@TableField 表示非主键字段
- 字段和属性名不同时使用(驼峰无需使用)
- bean中的属性在表中没有对应字段时
exist=false
- 不想某个字段被查出
select = false
@TableName("sys_user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField
private String name;
@TableField(select = false)
private Integer age;
@TableField(value = "email")
private String mail;
@TableField(exist = false)
private String address;
}
CRUD操作
插入
@Test
public void testInsert() {
User user = new User();
user.setName("qiuyu");
user.setAge(18);
user.setMail("66");
int i = userDao.insert(user);
System.out.println(i);
}
如果要id自增记得给id加上@TableId(type = IdType.AUTO)
更新
UpdateById
根据传入的对象的ID属性来修改
@Test
public void testUpdatebyId() {
User user = new User();
user.setId(6L);
user.setName("qiuyu666");
user.setAge(99);
user.setMail("77");
userDao.updateById(user);
}
Update
条件更新,使用QueryWrapper
@Test
public void testUpdate() {
User user = new User();
user.setName("qiuyu666");
user.setAge(99);
user.setMail("77");
//建立一个条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//如果表中的id = 7
queryWrapper.eq("id", 7L);
//把对象放入表中
userDao.update(user,queryWrapper);
}
或者使用UpdateWrapper,不传入对象,直接set要改的属性
@Test
public void testUpdate2() {
//建立一个条件
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
//如果表中的id = 7,直接改
updateWrapper
.eq("id", 7L)
.set("name","qiuyu9999");
//执行修改
userDao.update(null,updateWrapper);
}
}
删除
deleteById
@Test
public void testDeleteById() {
userDao.deleteById(9);
}
deleteByMap
多条件删除 须同时满足多个条件
@Test
public void testDeleteByMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "qiuyu");
map.put("age", 18);
userDao.deleteByMap(map);
}
delete
条件删除,满足条件的全删了
//方法一 eq填的不是属性名而是表中的字段名
@Test
public void testDelete() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "qiuyu")
.eq("age",18);
userDao.delete(queryWrapper);
}
//方法二(推荐,无需写字段名)
@Test
public void testDelete2() {
User user = new User();
user.setAge(88);
QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
userDao.delete(queryWrapper);
}
deleteBatchIds
@Test
public void testDeleteBatch() {
userDao.deleteBatchIds(Arrays.asList(7,14));
}
查询
selectById
@Test
public void testSelectById() {
User user = userDao.selectById(1);
System.out.println(user);
}
selectBatchIds
批量按ID查询
@Test
public void testSelectBatch() {
List<User> users = userDao.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
selectOne 查一条
根据条件查询一条数据,如果结果超过一条会报错
@Test
public void testSelectOne() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","qiuyu666");
User user = userDao.selectOne(queryWrapper);
System.out.println(user);
}
selectList 查询多条
@Test
public void testSelectList() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","qiuyu666");
List<User> users = userDao.selectList(queryWrapper);
users.forEach(System.out::println);
}
selectCount 查询条数
@Test
public void testSelectCount() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","qiuyu666");
Integer integer = userDao.selectCount(queryWrapper);
System.out.println(integer);
}
分页查询
配置
配置了才能使用分页功能
package com.qiuyu.config;
@Configuration
public class MPConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
查询
@Test
public void testSelectPage() {
IPage<User> page = new Page(2,3);
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.like("name", "qiu");
userDao.selectPage(page, queryWrapper);
System.out.println(page.getPages()); //总页数
System.out.println(page.getTotal()); //总数据条数
System.out.println(page.getSize()); // 每页数量
System.out.println(page.getCurrent()); //当前页
//查出的数据
for (User record : page.getRecords()) {
System.out.println(record);
}
}
配置
常用
mybatis-plus:
mapper-locations: "classpath*:/mapper/**/*.xml" #加载mapper
type-aliases-package: "com.qiuyu.bean" #别名
configuration:
use-generated-keys: true
map-underscore-to-camel-case: true #驼峰映射
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #日志
global-config:
db-config:
id-type: auto #id自增
基础配置
configLocation
导入mybatis的配置文件
mybatis-plus:
config-location: classpath:mybatis-config.xml
mapperLocations
配置mapper对应的xml文件所在的位置
mybatis-plus:
mapper-locations: "classpath*:/mapper/**/*.xml" #加载mapper
Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件)
typeAliasesPackage
MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使
用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。
mybatis-plus:
type-aliases-package: "com.qiuyu.bean" #别名
configuration配置
map-underscore-to-camel-case
是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属
性名 aColumn(驼峰命名) 的类似映射。
注意:
此属性在 MyBatis 中原默认值为 false,在 MyBatis-Plus 中,此属性也将用于生成最终的 SQL 的 select body
如果您的数据库命名符合规则无需使用 @TableField 注解指定数据库字段名
mybatis-plus:
configuration:
map-underscore-to-camel-case: true #驼峰映射
log
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #日志
DB策略
idType
全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。
mybatis-plus:
global-config:
db-config:
id-type: auto
tablePrefix
表名前缀,全局配置后可省略@TableName()配置。
mybatis-plus:
global-config:
db-config:
table-prefix: _tb
条件构造器Wrapper
AllEq
//按照条件查询,如果map中有null,数据库中的值也得是null
allEq(BiPredicate<R, V> filter, Map<R, V> params)
//按照条件查询,如果map中有null,会忽略这个字段
allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
@Test
public void testWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//设置条件
Map<String,Object> params = new HashMap<>();
params.put("name", "曹操");
params.put("age", "20");
params.put("password", null);
//SELECT * FROM tb_user WHERE password IS NULL AND name = ? AND age = ?
wrapper.allEq(params);
//SELECT * FROM tb_user WHERE name = ? AND age = ?
wrapper.allEq(params,false);
//SELECT * FROM tb_user WHERE name = ? AND age = ?
wrapper.allEq((k, v) -> (k.equals("name") || k.equals("age")), params);
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
基本比较
- eq
等于 = - ne
不等于 <> - gt
大于 > - ge
大于等于 >= - lt
小于 < - le
小于等于 <= - between
BETWEEN 值1 AND 值2 - notBetween
NOT BETWEEN 值1 AND 值2 - in
字段 IN (value.get(0), value.get(1), …) - notIn
字段 NOT IN (v0, v1, …)
@Test
public void testEq() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE password = ? AND age >= ? AND name IN (?,?,?)
wrapper.eq("password", "123456")
.ge("age", 20)
.in("name", "李四", "王五", "赵六");
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
模糊查询
-
like
- LIKE ‘%值%’
- 例: like(“name”, “王”) —> name like ‘%王%’
-
notLike
- NOT LIKE ‘%值%’
- 例: notLike(“name”, “王”) —> name not like ‘%王%’
-
likeLeft
- LIKE ‘%值’
- 例: likeLeft(“name”, “王”) —> name like ‘%王’
-
likeRight
- LIKE ‘值%’
- 例: likeRight(“name”, “王”) —> name like ‘王%’
@Test
public void testWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE name LIKE ?
//Parameters: %曹%(String)
wrapper.like("name", "曹");
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
排序
-
orderBy
-
排序:ORDER BY 字段, …
-
例: orderBy(true, true, “id”, “name”) —> order by id ASC,name ASC
-
-
orderByAsc
- 排序:ORDER BY 字段, … ASC
- 例: orderByAsc(“id”, “name”) —> order by id ASC,name ASC
-
orderByDesc
- 排序:ORDER BY 字段, … DESC
- 例: orderByDesc(“id”, “name”) —> order by id DESC,name DESC
@Test
public void testWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user ORDER BY age DESC
wrapper.orderByDesc("age");
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
逻辑查询
-
or
- 拼接 OR
- 主动调用or 表示紧接着下一个方法不是用and 连接!(不调用or 则默认为使用and 连接)
-
and
- AND 嵌套
- 例: and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”)) —> and (name = ‘李白’ and status<> ‘活着’)
@Test
public void testWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE name = ? OR
age = ?
wrapper.eq("name","李四").or().eq("age", 24);
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
查询指定字段
在MP查询中,默认查询所有的字段,如果有需要也可以通过select方法进行指定字段。
@Test
public void testWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,name,age FROM tb_user WHERE name = ? OR age = ?
wrapper.eq("name", "李四")
.or()
.eq("age", 24)
.select("id", "name", "age");
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}