mybatis返回map类型数据空值字段不显示(三种解决方法)

本文介绍如何在MyBatis中处理查询结果为空的情况,包括使用IFNULL进行字段空值判断、通过设置callSettersOnNulls配置项来控制空值行为以及自定义TypeHandler返回特定默认值的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、查询sql添加每个字段的判断空

IFNULL(rate,'') as rate
  • 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

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

如果想要配置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

在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>