queryWrapper是mybatis plus中实现查询的对象封装操作类,可以封装sql对象,包括where条件,order by排序,select哪些字段等等,他的层级关系如下:
Wrapper:条件构造抽象类,最顶端父类;
AbstractWrapper:用于查询条件封装,生成sql的where条件;
AbstractLambdaWrapper:Lambda语法使用Wrapper统一处理解析lambda获取column。
LambdaQueryWrapper:用于lambda语法使用的查询Wrapper;
LambdaUpdateWrapper:Lambda更新封装Wrapper;
QueryWrapper:Entity对象封装操作类,不是用lambda;
UpdateWrapper:Update条件封装,用于Entity对象更新操作。
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`name` varchar(255) DEFAULT NULL COMMENT '用户姓名',
`age` int(2) DEFAULT NULL COMMENT '用户年龄',
`email` varchar(255) DEFAULT NULL COMMENT '邮箱',
`del_flag` int(1) DEFAULT '0' COMMENT '删除标识 0:正常 1:删除 默认0',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户表';
创建Springboot项目,集成mybatis-plus、web、mysql等相关依赖;搭建基础的demo操作:
(1)pom.xml:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.3version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
(2)配置application.yml
# 服务端口
server:
port: 8083
# 数据源配置
spring:
datasource:
name: test
url: jdbc:mysql://localhost:3306/db_order?&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSl=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
## 配置连接池信息
## 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 30
## 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 超过时间限制是否回收
removeAbandoned: true
# 超时时间;单位为秒。180秒=3分钟
removeAbandonedTimeout: 180
# 关闭abanded连接时输出错误日志
logAbandoned: true
# mybatis-plus 默认扫描mapper.xml的目录
mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml
#配置sql打印日志
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
(3)创建一个实体类:
/**
* @author qzz
*/
@Data
@TableName("t_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用户id
*/
@TableId(value="id", type = IdType.AUTO)
private Integer id;
/**
* 名称
*/
@TableField("name")
private String name;
/**
* 年龄
*/
@TableField("age")
private Integer age;
/**
* 删除标识 0:正常 1:删除 默认0
*/
@TableField("del_flag")
private Integer del_flag;
/**
* 邮箱
*/
@TableField("email")
private String email;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date create_time;
/**
* 修改时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date update_time;
}
(4)编写一个mapper接口,只需继承BaseMapper,基本的单表查询都给你封装好了。
/**
* @author qzz
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
}
官网上可以看到有很多条件构造器,下面将使用几个常用的作为示例进行使用,其实本质还是sql语句,如果想要打印sql日志,可以在application.yml文件中进行如下的配置:
mybatis-plus:
#配置sql打印日志
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Wrapper是一个接口,官方提供了很多的实现类,我们通过其实现类去构造wrapper对象即可。
过滤条件:
sql实现:
select * from t_user
where del_flag = 0
<if test ="name!=null and ''!=name">
and name like concat('%',#{name},'%')
</if>
order by create_time desc
queryWrapper实现:
/**
* 案例一:根据name模糊查看未删除的用户列表信息
* @param name
* @return
*/
@RequestMapping("/list")
public Map<String,Object> getList(@RequestParam String name){
Map<String,Object> result = new HashMap<>();
//构建一个查询的wrapper
QueryWrapper<User> wrapper = new QueryWrapper<User>();
//name不为空时,组装模糊查询条件
wrapper.like(StringUtils.isNotBlank(name),"name",name);
//未删除
wrapper.eq("del_flag",0);
//创建时间降序
wrapper.orderByDesc("create_time");
List<User> list = userMapper.selectList(wrapper);
result.put("data",list);
return result;
}
启动项目,运行接口http://localhost:8083/user/list?name=小
测试,控制台sql如下:
sql实现:
select * from t_user
where del_flag = 0
and name like concat('李','%')
and email is not null
order by create_time desc
queryWrapper实现:
/**
* 案例二:查看姓张的并且邮箱不为空的用户列表
* @return
*/
@RequestMapping("/list2")
public Map<String,Object> getList2(){
Map<String,Object> result = new HashMap<>();
//构建一个查询的wrapper
QueryWrapper<User> wrapper = new QueryWrapper<User>();
//姓张的
wrapper.likeRight("name","张");
//邮箱不为空
wrapper.isNotNull("email");
//未删除
wrapper.eq("del_flag",0);
//创建时间降序
wrapper.orderByDesc("create_time");
List<User> list = userMapper.selectList(wrapper);
result.put("data",list);
return result;
}
sql实现:
select * from t_user
where del_flag=0
and age between 20 and 30
order by create_time desc
queryWrapper实现:
/**
* 案例三:年龄范围查询(20-30之间的)
* @return
*/
@RequestMapping("/list3")
public Map<String,Object> getList3(){
Map<String,Object> result = new HashMap<>();
//构建一个查询的wrapper
QueryWrapper<User> wrapper = new QueryWrapper<User>();
//年龄20-30之间的
wrapper.between("age",20,30);
//未删除
wrapper.eq("del_flag",0);
//创建时间降序
wrapper.orderByDesc("create_time");
List<User> list = userMapper.selectList(wrapper);
result.put("data",list);
return result;
}
sql实现:
select * from t_user
where del_flag=0
and DATE(create_time) = STR_TO_DATE('2021-08-13','%Y-%m-%d')
order by create_time desc
queryWrapper实现:
/**
* 案例四:根据createTime查看当日的用户列表
* @return
*/
@RequestMapping("/list4")
public Map<String,Object> getList4(@RequestParam String createTime){
Map<String,Object> result = new HashMap<>();
//构建一个查询的wrapper
QueryWrapper<User> wrapper = new QueryWrapper<User>();
//查询条件为创建时间
wrapper.apply(StringUtils.isNotBlank(createTime),"DATE(create_time) = STR_TO_DATE('"+createTime+"','%Y-%m-%d')");
//未删除
wrapper.eq("del_flag",0);
//创建时间降序
wrapper.orderByDesc("create_time");
List<User> list = userMapper.selectList(wrapper);
result.put("data",list);
return result;
}
sql实现:
select * from t_user
where del_flag=0
and DATE(create_time) >= STR_TO_DATE('2021-08-01','%Y-%m-%d')
AND DATE(create_time) <= STR_TO_DATE('2021-08-13','%Y-%m-%d')
order by create_time desc
queryWrapper实现:
/**
* 案例五:查看某个时间段内的用户列表
* @return
*/
@RequestMapping("/list5")
public Map<String,Object> getList5(@RequestParam String startTime,@RequestParam String endTime){
Map<String,Object> result = new HashMap<>();
//构建一个查询的wrapper
QueryWrapper<User> wrapper = new QueryWrapper<User>();
//查询条件为创建时间
wrapper.apply(StringUtils.isNotBlank(startTime),"DATE(create_time) >= STR_TO_DATE('"+startTime+"','%Y-%m-%d')");
wrapper.apply(StringUtils.isNotBlank(endTime),"DATE(create_time) <= STR_TO_DATE('"+endTime+"','%Y-%m-%d')");
//未删除
wrapper.eq("del_flag",0);
//创建时间降序
wrapper.orderByDesc("create_time");
List<User> list = userMapper.selectList(wrapper);
result.put("data",list);
return result;
}
sql实现:
select * from t_user
where del_flag=0
and name like concat('李','%')
and (email is not null or age>16)
order by create_time desc
queryWrapper实现:
and方法嵌套使用
/**
* 案例六:查询姓李的并且邮箱不为空或者是年龄大于16的用户
* @return
*/
@RequestMapping("/list6")
public Map<String,Object> getList6(){
Map<String,Object> result = new HashMap<>();
//构建一个查询的wrapper
QueryWrapper<User> wrapper = new QueryWrapper<User>();
//and方法嵌套
wrapper.likeRight("name","李").and(
userQueryWrapper -> userQueryWrapper.isNotNull("email")
.or().lt("age",16)
);
//未删除
wrapper.eq("del_flag",0);
//创建时间降序
wrapper.orderByDesc("create_time");
List<User> list = userMapper.selectList(wrapper);
result.put("data",list);
return result;
}
sql实现:
select * from t_user
where del_flag=0
and id in(1,2,3)
order by create_time desc
queryWrapper实现:
/**
* 案例七:根据ids查看用户列表信息
* @return
*/
@RequestMapping("/list7")
public Map<String,Object> getList7(@RequestParam String ids){
Map<String,Object> result = new HashMap<>();
//构建一个查询的wrapper
QueryWrapper<User> wrapper = new QueryWrapper<User>();
if(StringUtils.isNotBlank(ids)){
//字符串转数组再转List
Collection<String> collection = Arrays.asList(ids.split(","));
//in方法
wrapper.in(collection.size()>0,"id",collection);
}
//未删除
wrapper.eq("del_flag",0);
//创建时间降序
wrapper.orderByDesc("create_time");
List<User> list = userMapper.selectList(wrapper);
result.put("data",list);
return result;
}
可点击此处下载!
本文介绍就到这里了,感兴趣的小伙伴可以自行测试哦。