基本查询
/**
* id=?
*/
@Test
void selectById() {
User user = mapper.selectById(1087982257332887553L);
System.out.println(user);
}
/**
* id IN ( ? , ? , ? )
*/
@Test
void retrieveByIds() {
List<User> users = mapper.selectBatchIds(Arrays.asList(8, 9, 10));
users.forEach(System.out::println);
}
/**
* 根据map查询,key为column,value为具体的值
* name = ? AND age = ?
*/
@Test
void retrieveByMap() {
Map<String, Object> map = new HashMap<>();
map.put("name", "大boss");
map.put("age", "40");
List<User> users = mapper.selectByMap(map);
users.forEach(System.out::println);
}
条件构造器查询
/**
* 名字中包含雨并且年龄小于40
* name like '%雨%' and age<40
*/
@Test
void selectByWrapper1() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", "雨")
.lt("age", 40);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 名字中包含雨年并且龄大于等于20且小于等于40并且email不为空
* name like '%雨%' and age between 20 and 40 and email is not null
*/
@Test
void selectByWrapper2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", "雨")
.between("age", 20, 40)
.isNotNull("email");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
* name like '王%' or age>=25 order by age desc,id asc
*/
@Test
void selectByWrapper3() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.likeRight("name", "王")
.or().ge("age", 25)
.orderByDesc("age")
.orderByAsc("id");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 创建日期为2019年2月14日并且直属上级为名字为王姓
* date_format(create_time,'%Y-%m-%d')='2019-02-14' and
* manager_id in (select id from user where name like '王%')
*/
@Test
void selectByWrapper4() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.apply("date_format(create_time,'%Y-%m-%d')={0}", "2019-02-14")
.inSql("manager_id", "select id from user where name like '王%'");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* and中传入lambda
* <p>
* 名字为王姓并且(年龄小于40或邮箱不为空)
* name like '王%' and (age<40 or email is not null)
*/
@Test
void selectByWrapper5() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.likeRight("name", "王").
and(wq -> wq.lt("age", 40)
.or().isNotNull("email"));
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)
* name like '王%' or (age<40 and age>20 and email is not null)
*/
@Test
void selectByWrapper6() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.likeRight("name", "王").
or(wq -> wq.lt("age", 40)
.gt("age", 20)
.isNotNull("email"));
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* ( 年龄小于40或邮箱不为空)并且名字为王姓
* (age<40 or email is not null) and name like '王%'
*/
@Test
void selectByWrapper7() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.nested(wq -> wq.lt("age", 40)
.or().isNotNull("email"))
.likeRight("name", "王");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 年龄为30、31、34、35
*/
@Test
void selectByWrapper8() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.in("age", Arrays.asList(30, 31, 34, 35));
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 只返回满足条件的其中一条语句即可 limit 1
*/
@Test
void selectByWrapper9() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.in("age", Arrays.asList(30, 31, 34, 35)).last("limit 1");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
指定列与排除列
/**
* 查询指定列
* SELECT id,name FROM user WHERE (name LIKE ?)
*/
@Test
void selectPart1() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("id", "name").like("name", "雨");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 排除指定列
* SELECT id,name,age,manager_id FROM user WHERE (name LIKE ?)
*/
@Test
void selectPart2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select(User.class, info -> !info.getColumn().equals("create_time") &&
!info.getColumn().equals("email")
).like("name", "雨");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
Condition处理参数 拼接动态语句
@Test
void testCondition(){
String name = "王";
String email = "";
//withOutCondition(name,email);
withCondition(name,email);
}
private void withOutCondition(String name,String email){
QueryWrapper<User> wrapper = new QueryWrapper<>();
if(StringUtils.isNotBlank(name)){
wrapper.like("name",name);
}
if(StringUtils.isNotBlank(email)){
wrapper.like("email",email);
}
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
private void withCondition(String name,String email){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like(StringUtils.isNotBlank(name),"name",name)
.like(StringUtils.isNotBlank(email),"email",email);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
以实体作为参数
/**
* WHERE name=? AND age=?
* 以实体为参数 和普通设置参数 互不干扰, 都会存在, 使用时需慎重
* 以实体为参数,默认是等值的,需要使用@TableField注解,并注明sqlCondition
*/
@Test
void selectByWrapperEntity(){
User user = new User();
user.setName("天乔巴夏");
user.setAge(20);
QueryWrapper<User> wrapper = new QueryWrapper<>(user);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
@TableField(value = "name",condition = SqlCondition.LIKE) //指定字段名
private String name;
AllEq的使用
@Test
void selectByWrapperAllEq(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
Map<String,Object> params = new HashMap<>();
params.put("name","天乔巴夏");
params.put("age",null); // age is null , 可以通过 下面这句设置 false
wrapper.allEq(params,false);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
@Test
void selectByWrapperAllEq2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
Map<String, Object> params = new HashMap<>();
params.put("name", "天乔巴夏");
params.put("age", null); // age is null , 可以通过 下面这句设置 false
wrapper.allEq((k, v) -> !k.equals("name"), params, false);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
自定义查询
注解形式
public interface UserMapper extends BaseMapper<User> {
@Select("select * from user ${ew.customSqlSegment}")
List<User> selectAll(@Param(Constants.WRAPPER)Wrapper<User> wrapper);
}
/**
* 测试自定义方法 注解
*/
@Test
void selectByCustomAnno(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","天乔巴夏");
List<User> users = mapper.selectAll(wrapper);
users.forEach(System.out::println);
}
xml形式
public interface UserMapper extends BaseMapper<User> {
List<User> selectAll2(@Param(Constants.WRAPPER)Wrapper<User> wrapper);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hyh.mybatisplus.mapper.UserMapper">
<select id="selectAll2" resultType="com.hyh.mybatisplus.entity.User">
select * from user ${ew.customSqlSegment}
</select>
</mapper>
其他的查询
/**
* 优雅返回指定字段的结果
*/
@Test
void selectByWrapperMaps1() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", "雨")
.lt("age", 40)
.select("id","name");
List<Map<String, Object>> mapList = mapper.selectMaps(wrapper);
mapList.forEach(System.out::println);
}
/**
* 按照直属上级分组,查询每组的平均年龄、最大年龄、最小年龄。
* 并且只取年龄总和小于500的组。
*
* select avg(age) avg_age,min(age) min_age,max(age) max_age
* from user
* group by manager_id
* having sum(age) <500
*/
@Test
void selectByWrapperMaps2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("avg(age) avg_age","min(age) min_age","max(age) max_age")
.groupBy("manager_id").having("sum(age)<{0}",500);
List<Map<String, Object>> mapList = mapper.selectMaps(wrapper);
mapList.forEach(System.out::println);
}
/**
* 查个数
*/
@Test
void selectCount() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name","雨");
Integer cnt = mapper.selectCount(wrapper);
System.out.println(cnt);
}
/**
* 查一个实体
*/
@Test
void selectOne(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","天乔巴夏");
User user = mapper.selectOne(wrapper);
System.out.println(user);
}
/**
* lambda构造,编译时检查字段信息,防止误写
*/
@Test
void selectLambda(){
//LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
//LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
LambdaQueryWrapper<User> lambdaQuery = Wrappers.<User>lambdaQuery();
lambdaQuery.like(User::getName,"雨").lt(User::getAge,40);
// where name like '%雨%'
List<User> users = mapper.selectList(lambdaQuery);
users.forEach(System.out::println);
}
Mybatis Plus各种查询方法
package com.xiao.permission_system;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.mysql.cj.util.StringUtils;
import com.xiao.permission_system.entity.UserInfo;
import com.xiao.permission_system.mapper.UserInfoMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PermissionSystemApplicationTests {
@Test
public void contextLoads() {
}
@Autowired
private UserInfoMapper userInfoMapper;
/**
* 普通查询
*/
@Test
public void selectById() {
UserInfo userInfo = userInfoMapper.selectById(123);
System.out.println(userInfo);
}
/**
* 批量查询
*/
@Test
public void selectByIds() {
List<Long> ids = Arrays.asList(123L,124L,125L);
List<UserInfo> userInfo = userInfoMapper.selectBatchIds(ids);
System.out.println(userInfo);
}
/**
* 名字包含娟并且年龄小雨30
*/
@Test
public void selectByWrapper() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.like("username","娟").lt("age",30);
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 名字包含娟并且年龄大雨等于20且小于等于40并且email不为空
*/
@Test
public void selectByWrapper2() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.like("username","娟").between("age",20,30).isNotNull("email");
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 名字姓肖或者年量大雨等于20,按照年龄降序排列,年龄相同按照id生序排列
*/
@Test
public void selectByWrapper3() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.likeRight("username","肖")
.or().ge("age",20).orderByDesc("age").orderByAsc("id");
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 创建日期为2019年10月2日并且直属上级名字为王姓
*/
@Test
public void selectByWrapper4() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.apply("date_format(create_time,'%Y-%m-%d')={0}","2019-10-07")
.inSql("parent_id","select id from user where username like '王%'");
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 名字为王姓并且(年龄小于40或邮箱不为空)
*/
@Test
public void selectByWrapper5() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.likeRight("username","王")
.and(wq->wq.lt("age",40))
.or().isNotNull("email");
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 名字为王姓并且(年龄小于40并且大与20或邮箱不为空)
*/
@Test
public void selectByWrapper6() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.likeRight("username","王")
.and(wq->wq.lt("age",40).gt("age",20))
.or().isNotNull("email");
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* (年龄小于40并且大与20或邮箱不为空)名字为王姓并且
*/
@Test
public void selectByWrapper7() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.nested(wq->wq.lt("age",40))
.or().isNotNull("email")
.likeRight("username","王");
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 年龄23,30,40
*/
@Test
public void selectByWrapper8() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.in("age",Arrays.asList(20,30,40));
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 只返回满足条件的其中一条语句即可
*/
@Test
public void selectByWrapper9() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.in("age",Arrays.asList(20,30,40)).last("limit 1");
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 名字中包含雨并且年龄小于40(只取id,username)
*/
@Test
public void selectByWrapper10() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.select("id","username").like("username","雨").lt("age",40);
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 名字中包含雨并且年龄小于40(不取create_time,parent_id两个字段,即不列出全部字段)
*/
@Test
public void selectByWrapper11() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.like("username","雨").lt("age",40)
.select(UserInfo.class,info->!info.getColumn().equals("create_time")&&
!info.getColumn().equals("parent_id"));
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 姓名和邮箱不为空
*/
public void testCondition() {
String username = "王";
String email = "";
condition(username,email);
}
private void condition(String username,String email){
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.like(StringUtils.isNullOrEmpty(username),"name",username)
.like(StringUtils.isNullOrEmpty(email),"email",email);
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 实体作为条件构造器方法的参数
*/
@Test
public void selectByWrapperEntity() {
UserInfo whereUser = new UserInfo();
whereUser.setUsername("xiaojuan");
whereUser.setAge(22);
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>(whereUser);
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* AllEq用法
*/
@Test
public void selectByWrapperAllEq() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
Map<String, Object> params = new HashMap<String, Object>();
params.put("nuserame","xiaojuan");
params.put("age",null);
queryWrapper.allEq(params);
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* AllEq用法(排除不是条件的字段)
*/
@Test
public void selectByWrapperAllEq2() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
Map<String, Object> params = new HashMap<String, Object>();
params.put("nuserame","xiaojuan");
params.put("age",null);
queryWrapper.allEq((k,v)->!k.equals("name"),params);
List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* selectMaps
*/
@Test
public void selectByWrapperMaps() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.like("name","肖").lt("age",40);
List<Map<String,Object>> userInfoList = userInfoMapper.selectMaps(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* 按照直属上级分组,查询每组的平均年龄,最大年龄,最小年龄。并且只取年龄总和小于500的组
*/
@Test
public void selectByWrapperMaps2() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.select("avg(age) avg_age","min(min) min_age","max(age) max_age")
.groupBy("parent_id").having("sum(age)<{0}",500);
List<Map<String,Object>> userInfoList = userInfoMapper.selectMaps(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* selectObjs
*/
@Test
public void selectByWrapperObjs() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.select("id","name").like("name","肖").lt("age",40);
List<Object> userInfoList = userInfoMapper.selectObjs(queryWrapper);
userInfoList.forEach(System.out::println);
}
/**
* selectCount
*/
@Test
public void selectByWrapperCount() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.like("name","肖").lt("age",40);
Integer count = userInfoMapper.selectCount(queryWrapper);
System.out.println(count);
}
/**
* selectOne
*/
@Test
public void selectByWrapperSelectOne() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.like("name","肖").lt("age",40);
UserInfo user = userInfoMapper.selectOne(queryWrapper);
System.out.println(user);
}
/**
* 使用Lambda
*/
@Test
public void selectLambda() {
// LambdaQueryWrapper<UserInfo> lambda = new QueryWrapper<UserInfo>().lambda();
LambdaQueryWrapper<UserInfo> lambda = new LambdaQueryWrapper<UserInfo>();
lambda.like(UserInfo::getUsername,"娟").lt(UserInfo::getAge,40);
List<UserInfo> userInfoList = userInfoMapper.selectList(lambda);
userInfoList.forEach(System.out::println);
}
/**
* 使用Lambda,名字为王姓(年龄小于40或邮箱不为空)
*/
@Test
public void selectLambd2() {
LambdaQueryWrapper<UserInfo> lambda = new LambdaQueryWrapper<UserInfo>();
lambda.like(UserInfo::getUsername,"娟")
.and(lqw->lqw.lt(UserInfo::getAge,40).or().isNotNull(UserInfo::getEmail));
List<UserInfo> userInfoList = userInfoMapper.selectList(lambda);
userInfoList.forEach(System.out::println);
}
/**
* 使用Lambda链式
*/
@Test
public void selectLambd3() {
List<UserInfo> userInfoList = new LambdaQueryChainWrapper<UserInfo>(userInfoMapper)
.like(UserInfo::getUsername,"娟").ge(UserInfo::getAge,20).list();
userInfoList.forEach(System.out::println);
}
}