Mybatis返回的对象列表包含null

一直以为Mybatis返回的POJO对象列表不会包含null,所以肆无忌惮的取出元素直接获取属性值。
直到一天,程序报了NPE。
看例子

一个POJO类

package com.xxx.mybatistest.entity;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class NullTest {

	private Long id;
	
	private String testName;
}

Mapper

package com.xxx.mybatistest.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.xxx.mybatistest.entity.NullTest;

@Mapper
public interface NullTestMapper {

	List<NullTest> queryList();
}

Xml

<?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.xxx.mybatistest.mapper.NullTestMapper">
    <select id="queryList" resultType="com.xxx.mybatistest.entity.NullTest">
        select a.id, a.testName, a.ext from (
       	  select null as id, null as testName, '1' as ext
       	  union all
       	  select 1235 as id, 'test1' as testName, '1' as ext
       	  union all
       	  select 76543 as id, null as testName, '1' as ext
       	  union all
       	  select null as id, null as testName, '1' as ext
       	  union all
       	  select null as id, 'test2' as testName, '1' as ext
       	  union all
       	  select null as id, null as testName, '1' as ext
        ) a
    </select>
</mapper>

Service

package com.xxx.mybatistest.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxx.mybatistest.entity.NullTest;
import com.xxx.mybatistest.mapper.NullTestMapper;
import com.xxx.mybatistest.service.NullTestService;

@Service
public class NullTestServiceImpl implements NullTestService {
	
	@Autowired
	private NullTestMapper nullTestMapper;

	@Override
	public List<NullTest> queryList() {
		List<NullTest> list = nullTestMapper.queryList();
		System.out.println(list);
		return list;
	}

}

结果竟然包含了好几个null

[null,
{
	"id": 1235,
	"testName": "test1"
},
{
	"id": 76543,
	"testName": null
},
null,
{
	"id": null,
	"testName": "test2"
},
null]

结论

当Mybatis查询到的结果映射到的实体(包括Map)字段都为null时,则不实例化对象,而是直接返回null。
所以获取对象的字段前应该先做非null判断

for (NullTest nullTest : list) {
	if (nullTest != null) {
		System.out.println(nullTest.getTestName());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值