Mybatis-plus之QueryWrapper、QueryChainWrapper、LambdaQueryWrapper以及LambdaQueryChainWrapper用法
前言:以前都是使用QueryWrapper的情况多一点,其余三种也没怎么涉及。最近是因为优化一个项目,所以才突然想起。
首先准备一个对应的实体类:
@Data
@TableName("house")
public class HouseEntity {
@TableId(type = IdType.AUTO)
private Integer houseId;
private String houseOwner;
private String houseArea;
}
分别测试使用代码测试,都以查询所有的数据为目的。都注入
@Autowired
private HouseMapper houseMapper;
- QueryWrapper
@Test
public void test1() {
List<HouseEntity> list=houseMapper.selectList(new QueryWrapper<HouseEntity>()
.orderByDesc("house_area"));
System.out.println("QueryWrapper:"+list);
}
执行结果:QueryWrapper:[HouseEntity(houseId=2, houseOwner=LS, houseArea=72), HouseEntity(houseId=1, houseOwner=ZS, houseArea=70)]
- QueryChainWrapper
@Test
public void test() {
List<HouseEntity> list2=new QueryChainWrapper<>(houseMapper)
.orderByDesc("house_area").list();
System.out.println("QueryChainWrapper:"+list);
}
执行结果:QueryChainWrapper:[HouseEntity(houseId=2, houseOwner=LS, houseArea=72), HouseEntity(houseId=1, houseOwner=ZS, houseArea=70)]
- LambdaQueryWrapper
@Test
public void test3() {
List<HouseEntity> list=houseMapper.selectList(new LambdaQueryWrapper<HouseEntity>()
.orderByDesc(HouseEntity::getHouseArea));
System.out.println("LambdaQueryWrapper:"+list);
}
执行结果:LambdaQueryWrapper:[HouseEntity(houseId=2, houseOwner=LS, houseArea=72), HouseEntity(houseId=1, houseOwner=ZS, houseArea=70)]
- LambdaQueryChainWrapper
@Test
public void test3() {
List<HouseEntity> list = new LambdaQueryChainWrapper<>(houseMapper)
.orderByDesc(HouseEntity::getHouseArea).list();
System.out.println("LambdaQueryChainWrapper:"+list);
}
执行结果:LambdaQueryChainWrapper:[HouseEntity(houseId=2, houseOwner=LS, houseArea=72), HouseEntity(houseId=1, houseOwner=ZS, houseArea=70)]
总结:
QueryWrapper
、QueryChainWrapper
只能都只能指定需要的数据库列名LambdaQueryWrapper
、LambdaQueryChainWrapper
可以通过获取Lambda数据库列名QueryWrapper
、LambdaQueryWrapper
不能使用链式查询的方式,必须借助BaseMapper来执行QueryChainWrapper
、LambdaQueryChainWrapper
可以使用链式查询的方式,如list(),one()