一、selectMaps方法
应用场景一:表字段特别多,但是需求只要其中几个时,使用selectMaps更优雅
// SELECT id,name FROM user WHERE (name LIKE ? AND age < ?)
@Test
public void selectByWrapperMaps(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id","name").like("name","J").lt("age",40);
List<Map<String, Object>> userList = userMapper.selectMaps(queryWrapper);
userList.forEach(System.out::println);
}
应用场景二:统计查询中返回统计结果时
// SELECT avg(age) avg_age,min(age) min_age,max(age) max_age FROM user GROUP BY age HAVING sum(age) > ?
@Test
public void selectByWrapperMaps2(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("avg(age) avg_age","min(age) min_age","max(age) max_age")
.groupBy("age").having("sum(age) > {0}", 20);
List<Map<String, Object>> userList = userMapper.selectMaps(queryWrapper);
userList.forEach(System.out::println);
}
二、selectObjs方法
特点:只返回第一个字段的值,注意不是行,是列;比如上面例子就只返回id列的几个值;泛型因为不确定第一列会是什么类型,所以也是用Object类型。
List<Object> userList = userMapper.selectObjs(queryWrapper);
三、selectCount方法
特点:会自动生成select(count(1)),不能使用自定义select字段了,用的话会报错。
// SELECT COUNT( 1 ) FROM user WHERE (name LIKE ? AND age < ?)
@Test
public void selectByWrapperCount(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","J").lt("age",40);
Integer userList = userMapper.selectCount(queryWrapper);
System.out.println("总记录数为:"+userList);
}
四、selectOne方法
特点:只返回一条结果,查询结果必须是一条或者没有,如果有多条结果,会报错
// SELECT id,name,age,email FROM user WHERE (name LIKE ? AND age < ?)
@Test
public void selectByWrapperOne(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","Jack").lt("age",40);
User userList = userMapper.selectOne(queryWrapper);
System.out.println(userList);
}