mybatis3 空字段null字段不返回

Mybatis resultMap空值映射問題解決

Mybatis在使用resultMap來映射查詢結果中的列,如果查詢結果中包含空值的列(不是null),則Mybatis在映射的時候,不會映射這個字段,例如 查詢 name,sex,age,數據庫中的age字段沒有值,Mybatis返回的map中只映射了 name和sex字段,而age字段則沒有包含。

那么如何將age字段映射到map中呢。提供兩種解決方法:

使用Mybatis config配置

創建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>

配置Mybatis的SqlSessionFactoryBean

<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接口


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);
    }
    @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) throws SQLException { }}

繼續在resultMap中使用,即可配置age的默認值(上述代碼中age的默認值為"")

<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中已經移除。

 本文由用戶 chokee 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!