<select id="getArticleById" resultType="map">
select
*
from article t
</select>
当返回结果resultType为map时,如果表中字段为空,则返回的map中就会没有这个字段,有时候我们需要即使字段数据为空也要返回这个空字段。
解决方法:
1.查询sql添加每个字段的判断空
IFNULL(id,'') as id
不太建议这种方法,因为经常要使用select *获取,不能每个字段都要判断一下,太麻烦了。
2. 新建一个mybatis-configuration.xml文件
在里面填写如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL MAP Config 3.1//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="callSettersOnNulls" value="true"/>
</settings>
</configuration>
然后打开spring-mybatis.xml文件,将新建的mybatis-configuration.xml引进来
<!-- spring和MyBatis完美整合,添加mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--在这里将config文件引入-->
<property name="configLocation" value="classpath:mybatis-configuration.xml"/>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mapping/*.xml"></property>
</bean>
重启项目,会发现值为空的字段也出现在map中了
推荐使用第二种方法
补充:当map值返回为null,且又用json返回给前台,且前台用某些表格插件时会报错,因为转json时会将值为null的字段直接忽略,所以转json时最好这样写,加上SerializerFeature.WriteMapNullValue
return JSON.toJSONString(ret, SerializerFeature.WriteMapNullValue);
这样即使值为null转json后字段也不会消失