Mybatis resultMap空值映射问题解决

转自文章  http://www.oschina.net/question/1032714_224673


Mybatis在使用resultMap来映射查询结果中的列,如果查询结果中包含空值的列(不是null),则Mybatis在映射的时候,不会映射这个字段,例如 查询 name,sex,age,数据库中的age字段没有值,Mybatis返回的map中只映射了 name和sex字段,而age字段则没有包含。

那么如何将age字段映射到map中呢。提供两种解决方法:

使用Mybatis config配置

创建configuration.xml

?
1
2
3
4
5
6
7
8
<? 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 >

配置Mybatis的SqlSessionFactoryBean

?
1
2
3
4
5
6
< bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" >
     < property name = "dataSource" ref = "dataSource" />
     < property name = "configLocation" value = "classpath:/META-INF/spring/configuration.    xml" />
     < property name = "mapperLocations"
     value = "classpath:/META-INF/spring/mybatis/modelMap/*.xml" />
</ bean >

在这种配置中,age将以null值映射到map中。

如果想要配置age的默认值,则可以建立一个类,实现Mybatis的TypeHandler接口


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class EmptyStringIfNull implements TypeHandler<String> {
 
     @Override
     public String getResult(ResultSet rs, String columnName) throws SQLException {
      return (rs.getString(columnName) == null ) ? "" : rs.getString(columnName);
     }
 
     @Override
     public String getResult(ResultSet rs, int columnIndex) throws SQLException {
      return (rs.getString(columnIndex) == null ) ? "" : rs.getString(columnIndex);
     }
     <span></span> @Override
     public String getResult(CallableStatement cs, int columnIndex)   throws SQLException {
      return (cs.getString(columnIndex) == null ) ? "" : cs.getString(columnIndex);
     }
     @Override
     public void setParameter(PreparedStatement ps, int arg1, String str, JdbcType jdbcType) <span></span><span style= "font-size:9pt;line-height:1.5;" > throws SQLException {</span><span style= "font-size:9pt;line-height:1.5;" > }</span><span style= "font-size:9pt;line-height:1.5;" >}</span>

继续在resultMap中使用,即可配置age的默认值(上述代码中age的默认值为"")

?
1
2
3
4
5
< resultMap id = "list" type = "java.util.LinkedHashMap" >
     < result property = "name" column = "name" />
     < result property = "sex" column = "sex" />
     < result property = "age" column = "age" typeHandler = "com.demo.EmptyStringIfNull" />
</ resultMap >



网上有些资料中提到可以使用 defaultValue 和 nullValue的配置,但是这中配置是ibatis的用法,在Mybatis中已经移除。

写的不错,很有帮助,<setting name="callSettersOnNulls" value="true"/>好像需要mybatis3.2以上版本,实用的3.1.1启动就会出问题。
--- 共有 1 条评论 ---
  • last确实是要3.2+以上的版本,谢谢指出(9个月前)  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值