1. 程式人生 > >mybatis返回map型別資料空值欄位不顯示(三種解決方法)

mybatis返回map型別資料空值欄位不顯示(三種解決方法)

一、查詢sql新增每個欄位的判斷空

IFNULL(rate,'') as rate
  • 1
  • 1

二、ResultType利用實體返回,不用map

三、springMVC+mybatis查詢資料,返回resultType=”map”時,如果資料為空的欄位,則該欄位省略不顯示,可以通過新增配置檔案,規定查詢資料為空是則返回null。

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

spring-mybatis.xml

<!-- spring和MyBatis完美整合,新增mybatis的配置對映檔案 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
>
<property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-configuration.xml"/> <!-- 自動掃描mapping.xml檔案 --> <property name="mapperLocations" value="classpath:mapping/*.xml"></property> </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

如果想要配置rate的預設值,例如“”字串,則可以建立一個類,實現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 { }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

在sql.xml檔案定義與使用如下如下

<resultMap id="find" type="java.util.LinkedHashMap">
    <result property="name" column="name" />
    <result property="phone" column="phone" />
    <result property="rate" column="rate" typeHandler="com.mybatis.EmptyStringIfNull"/>
</resultMap>