Spring boot + MyBatis返回map中null值处理
程序员文章站
2024-03-19 18:57:28
...
在日常开发中,查询数据返回类型为map,数据库中有些自动值为null,则返回的结果中没有值为空的字段,则如何显示值为空的字段呢?
1.xml文件:
- <resultMap id="userLoginInfo" type="map" >
- <result column="uuid" property="id" />
- <result column="uuid2" property="uuid" />
- <result column="account" property="phone" />
- <result column="login_time" property="loginTime" />
- <result column="token" property="token" />
- <result column="data_progress" property="dataProgress" />
- <result column="account_locked" property="accountLocked" />
- <result column="is_delete" property="isDelete" />
- <result column="nickname" property="nickname" />
- <result column="user_head" property="userHead" />
- </resultMap>
- {accountLocked=false, loginTime=1480559610977, phone=18301413850, isDelete=false, dataProgress=0, nickname=,
- id=93cd68fcb95043febd28d6ad86666029, uuid=544dc45953e2dcc60e23ecccc52c578b, token=WT1Kgx}
经过各种查资料,总结以下解决方案:
解决方法一:
1、在Mybatis_config.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>
- <!--解决,查询返回结果含null没有对应字段值问题-->
- <setting name="callSettersOnNulls" value="true"/>
- </settings>
- </configuration>
备注:注意xml文件的头部引入的是mybaties-3-config.dtd
测试结果:
- {accountLocked=false, loginTime=1480559610977, userHead=null, phone=18301413850, isDelete=false, dataProgress=0, nickname=,
- id=93cd68fcb95043febd28d6ad86666029, uuid=544dc45953e2dcc60e23ecccc52c578b, token=WT1Kgx}
方法二:通过sql语句实现空值填充:
1、postgresql数据库:
select COALESCE(D.wk_ptn_cd, '00') as wk_ptn_cd
判断字段wk_ptn_cd是否为空,空给默认值‘00’,否则取该字段
2、非postgresql数据库:Mybatis使用IFNULL(P1,P2)函数
1.问题:
Mybatis中IFNULL(p1,p2)函数怎么用?
首先看没有IFNULL的查询:
2.1源代码:
select md.valueofdouble, md.periodcode
from meas_data md
WHERE objectcode="YQ"
AND datatime="2017-5-25 00:00:00"
AND measurementcode="PI_DRFDL"
- 1
- 2
- 3
- 4
- 5
2.2.截图:
3.1源代码:
select md.valueofdouble, IFNULL(md.periodcode,0)
from meas_data md
WHERE objectcode="YQ"
AND datatime="2017-5-25 00:00:00"
AND measurementcode="PI_DRFDL"
- 1
- 2
- 3
- 4
- 5
3.2截图:
4.总结:
1、IFNULL(P1,P2)如果如果P1不为空,则返回值为P1;P1为NULL,则返回为P2;P2有点类似替补球员;
2、注意,IFNULL只是针对局部字段的替换;如果整个结果查出来都是空,则不能使用IFNULL(P1,P2)
4.1源码:
select md.valueofdouble, md.periodcode
from meas_data md
WHERE objectcode="YQ"
AND datatime="2017-5-25 00:00:01"
AND measurementcode="PI_DRFDL"
- 1
- 2
- 3
- 4
- 5
4.2截图:
4.3源码:
select md.valueofdouble, IFNULL(md.periodcode,0)
from meas_data md
WHERE objectcode="YQ"
AND datatime="2017-5-25 00:00:01"
AND measurementcode="PI_DRFDL"
- 1
- 2
- 3
- 4
- 5
4.4截图:
上一篇: (9)学习tp5之模型
下一篇: 信号编程