// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
//根据id查询
User user = userMapper.selectById(1332883585346080769L);
代码:
//根据多个id,批量查询
@Test
public void findMany(){
List<Long> list = new ArrayList<>();
list.add(1L);
list.add(2L);
list.add(3L);
list.add(4L);
list.add(5L);
List<User> userList = userMapper.selectBatchIds(list);
for (User user : userList) {
System.out.println(user.getName());
}
}
结果:
代码:
//简单的条件查询(不常用)
@Test
public void testSelectByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name", "zibo");
map.put("age", 24);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
结果:
注意:map中的key对应的是数据库中的列名。例如数据库user_id,实体类是userId,这时map的key需要填写user_id;
MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能;
package com.zibo.mybatisplus.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.zibo.mybatisplus.mapper")
public class MybatisPlusConfig {
/*
* 乐观锁插件旧版本,已过时
*/
// @Bean
// public OptimisticLockerInterceptor optimisticLockerInterceptor() {
// return new OptimisticLockerInterceptor();
// }
/**
* 新版本插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//分页查询插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
/*
* 分页插件旧版本,已过时
*/
// @Bean
// public PaginationInterceptor paginationInterceptor() {
// return new PaginationInterceptor();
// }
}
直接new Page()对象,传入两个参数,当前页和每页显示的记录数,调用mp方法实现分页查询;
代码:
//分页查询
@Test
public void testPage(){
//创建page对象:当前页,每页展示的数据数量
Page<User> page = new Page<>(1,3);
//调用mp方法进行查询
Page<User> userPage = userMapper.selectPage(page, null);
//输出查询结果
System.out.println(userPage.getCurrent());//当前页
System.out.println(userPage.getRecords());//每页数据list集合
System.out.println(userPage.getSize());//每页显示记录数
System.out.println(userPage.getTotal());//总记录数
System.out.println(userPage.getPages());//总页数
System.out.println(userPage.hasNext());//是否有下一页
System.out.println(userPage.hasPrevious());//是否有上一页
}
结果:
物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除数据;
逻辑删除:假删除,将对应数据中代表是否被删除字段状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录;
代码实现:
//物理删除
@Test
public void deleteById(){
int result = userMapper.deleteById(1L);
System.out.println(result);
}
运行结果:
@Test
public void testDeleteBatchIds() {
int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10));
System.out.println(result);
}
@Test
public void testDeleteByMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Helen");
map.put("age", 18);
int result = userMapper.deleteByMap(map);
System.out.println(result);
}
ALTER TABLE `user` ADD COLUMN `deleted` boolean
并加上 @TableLogic 注解 和 @TableField(fill = FieldFill.INSERT) 注解
package com.zibo.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
import java.util.Date;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
//创建时间
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//更新时间
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
//版本号:用于乐观锁
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;
//逻辑删除
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
}
package com.zibo.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
//元对象处理器
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//创建填充
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);//metaObject元数据
this.setFieldValByName("updateTime",new Date(),metaObject);//metaObject元数据
//添加版本号
this.setFieldValByName("version", 1, metaObject);
//添加逻辑删除默认值0
this.setFieldValByName("deleted", 0, metaObject);
}
//更新填充
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);//metaObject元数据
}
}
此为默认值,如果你的默认值和mp默认的一样,该配置可无;
#mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=zibo15239417242
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#mybatis plus 逻辑删除标志位默认值
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
/**
* 测试 逻辑删除
*/
@Test
public void testLogicDelete() {
int result = userMapper.deleteById(4L);
System.out.println(result);
}
备注:mp3.3以上,不用添加插件了!
MyBatis Plus中查询操作也会自动添加逻辑删除字段的判断;
/**
* 测试 逻辑删除后的查询:
* 不包括被逻辑删除的记录
*/
@Test
public void testLogicDeleteSelect() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
性能分析拦截器,用于输出每条 SQL 语句及其执行时间;
SQL 性能执行分析,开发环境使用,超过指定时间,停止运行,有助于发现问题;
参数:maxTime: SQL 执行最大时长,超过自动停止运行,有助于发现问题;
参数:format: SQL是否格式化,默认false;
(性能分析插件已经被Mybatis Plus官方启用了,推荐使用第三方插件,我们这里使用的是最近版本的Spring Boot,相对应Mybatis Plus版本也是最新的3.4.0,所以在没有找到最准确的结果之前,暂时不做演示)
Wrapper : 条件构造抽象类,最顶端父类;
AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件;
AbstractLambdaWrapper : Lambda 语法使用 Wrapper统一处理解析 lambda 获取 column;
https://baomidou.com/guide/wrapper.html#abstractwrapper
ge(大于等于 >=)、gt(大于 >)、le(小于等于 <=)、lt(小于 <)、isNull(字段 IS NULL)、isNotNull(字段 IS NOT NULL);
@Test
public void testDelete() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.isNull("name")
.ge("age", 12)
.isNotNull("email");
int result = userMapper.delete(queryWrapper);
System.out.println("delete return count = " + result);
}
UPDATE user SET deleted=1 WHERE deleted=0 AND name IS NULL AND age >= ? AND email IS NOT NULL
注意:seletOne返回的是一条实体记录,当出现多条时会报错;
eq(等于 =)、ne(不等于 <>);
@Test
public void testSelectOne() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "Tom");
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 AND name = ?
包含大小边界;
between(BETWEEN 值1 AND 值2)、notBetween(NOT BETWEEN 值1 AND 值2);
@Test
public void testSelectCount() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.between("age", 20, 30);
Integer count = userMapper.selectCount(queryWrapper);
System.out.println(count);
}
SELECT COUNT(1) FROM user WHERE deleted=0 AND age BETWEEN ? AND ?
allEq:全部eq(或个别isNull);
个别参数说明: params:key为数据库字段名,value为字段值; null2IsNull:为true则在map的value为null时调用 isNull 方法,为false时则忽略value为null的;
@Test
public void testSelectList() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String, Object> map = new HashMap<>();
map.put("id", 2);
map.put("name", "Jack");
map.put("age", 20);
queryWrapper.allEq(map);
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 AND name = ? AND id = ? AND age = ?
selectMaps返回Map集合列表;
like(LIKE '%值%')、notLike(NOT LIKE '%值%')、likeLeft(LIKE '%值')、likeRight(LIKE '值%');
@Test
public void testSelectMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.notLike("name", "e")
.likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回
//值是Map列表
maps.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 AND name NOT LIKE ? AND email LIKE ?
in、notIn:
notIn("age",{1,2,3})--->age not in (1,2,3); notIn("age", 1, 2, 3)--->age not in (1,2,3);
inSql、notinSql:可以实现子查询:
例: 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);
@Test
public void testSelectObjs() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//queryWrapper.in("id", 1, 2, 3);
queryWrapper.inSql("id", "select id from user where id < 3");
List<Object> objects = userMapper.selectObjs(queryWrapper);//返回值
//是Object列表
objects.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 AND id IN (select id from user where id < 3)
注意:这里使用的是 UpdateWrapper;
不调用or则默认为使用 and ;
or(拼接 OR)、and(AND 嵌套);
@Test
public void testUpdate1() {
//修改值
User user = new User();
user.setAge(99);
user.setName("Andy");
//修改条件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper
.like("name", "h")
.or()
.between("age", 20, 30);
int result = userMapper.update(user, userUpdateWrapper);
System.out.println(result);
}
UPDATE user SET name=?, age=?, update_time=? WHERE deleted=0 AND name LIKE ? OR age BETWEEN ? AND ?
这里使用了lambda表达式,or中的表达式最后翻译成sql时会被加上圆括号;
@Test
public void testUpdate2() {
//修改值
User user = new User();
user.setAge(99);
user.setName("Andy");
//修改条件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper
.like("name", "h")
.or(i -> i.eq("name", "李白").ne("age", 20));
int result = userMapper.update(user, userUpdateWrapper);
System.out.println(result);
}
UPDATE user SET name=?, age=?, update_time=? WHERE deleted=0 AND name LIKE ? OR ( name = ? AND age <> ? )
orderBy(排序:ORDER BY 字段, ...)、orderByDesc(排序:ORDER BY 字段, ... DESC)、orderByAsc(排序:ORDER BY 字段, ... ASC);
@Test
public void testSelectListOrderBy() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 ORDER BY id DESC
直接拼接到 sql 的最后;
注意:只能调用一次,多次调用以最后一次为准 有sql注入的风险,请谨慎使用;
last(无视优化规则直接拼接到 sql 的最后);
@Test
public void testSelectListLast() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.last("limit 1");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 limit 1
@Test
public void testSelectListColumn() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id", "name", "age");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
SELECT id,name,age FROM user WHERE deleted=0
最终的sql会合并 user.setAge(),以及 userUpdateWrapper.set() 和 setSql() 中 的字段;
set(SQL SET 字段)、setSql(设置 SET 部分 SQL);
@Test
public void testUpdateSet() {
//修改值
User user = new User();
user.setAge(99);
//修改条件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper
.like("name", "h")
.set("name", "老李头")//除了可以查询还可以使用set设置修改的字段
.setSql(" email = '123@qq.com'");//可以有子查询
int result = userMapper.update(user, userUpdateWrapper);
}
UPDATE user SET age=?, update_time=?, name=?, email = '123@qq.com' WHERE deleted=0 AND name LIKE ?