一、 问题
开发中难免会遇到使用mybatis 进行数据查询,返回一个list 或者单个实体类(pojo类)的情况,但是mybatis在查询不到数据的时候处理方式并不同,如果接受数据后直接进行下一步的业务代码,则经常会遇到空指针异常(NullPointerException)
二、mybatis的两种处理方式
1. 若返回值为List集合,查询结果为空时会实例化一个空的集合对象,大小为0,并非为null。
2. 若返回值为pojo类,查询结果为空时,返回值为null。
三、代码验证
@Controller
public class TestController {
@Resource
private UsersMapper usersMapper;
@RequestMapping("user/{id}")
public void testtest(@PathVariable("id") int id){
User user = usersMapper.selectById( id);
List<User> userList = usersMapper.selectList();
if(user!=null){
System.out.println(user);
}else{
System.out.println("user为null");
}
if(userList!=null){
System.out.println("List的大小:" + userList.size());
}else{
System.out.println("List为null");
}
}
}
输出结果:
users为null
List的大小:0