Mybatis使用Map作为返回类型时,value值为空,字段被隐藏

Mybatis使用Map作为返回类型时,value值为空,字段被隐藏

编程文章jaq1232025-06-03 22:35:0210A+A-

问题描述

我们在项目中使用Mybatis进行查询数据的时候,根据场景需要返回值常常使用Map作为返回类型;

但是当数据库里面的值为空时,查询出来返回的Map对应的字段会被隐藏;

针对字段被隐藏的问题,进行如下的演示:

mapper接口

@Mapper
public interface SqlBaseMapper {
 List<Map<String, Object>> selectMapList();
}

SqlBaseMapper.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.xxkfz.simplememory.mapper.SqlBaseMapper">
      <select id="selectMapList" resultType="Map">
          select id        as id,
                 tmp_id    as tmpId,
                 temp_name as tempName,
                 temp_date as tempDate
          from temp
      </select>
</mapper>

测试结果:

[{TMPID=00003, ID=818020E3F66642308D9334F1B82A6F61, TEMPNAME=tmp测试数据3}, 
{TMPID=00001, ID=E74C9EC, TEMPNAME=xxkfz}, 
{TMPID=00006, ID=88640EF, TEMPNAME=temp测试数据3}]

可以看出,正因为temp_date数据库里值为空,返回的结果中该字段被隐藏了

解决方案

主要提供了以下几种解决办法:

  • 在配置文件application.yml添加配置
  mybatis:
    configuration:
      call-setters-on-nulls: true
  • 在配置文件mybatis.xml添加配置
 <?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
 <configuration>
     <settings>
         <setting name="callSettersOnNulls" value="true"/>
     </settings>
 </configuration>
  • sql解决(空值赋空)
   nvl(temp_date, ' ') as tempDate
  • 手动添加配置
 @Configuration
 public class MybatisConfig implements ApplicationContextAware {
 
     @Override
     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         SqlSessionFactory bean = applicationContext.getBean(SqlSessionFactory.class);
      org.apache.ibatis.session.Configuration configuration = bean.getConfiguration();
      configuration.setCallSettersOnNulls(true);
     }
 }


Mybatis使用Map作为返回类型时,value值为空,字段被隐藏的解决方案

点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21