Mybatis返回Map时,如果值为空的话,那么key也不会被加入到map中的解决办法

时间:2022-03-17 19:40:17

转自 : http://blog.csdn.net/renfufei/article/details/39646207



前提:

项目中集成Mybatis与Spring,使用的是Mybatis3.2.7,以及Spring4.0.5,mybatis-spring-1.2.2;

因为项目组成员想要偷懒,将数据从DB中查询出来时需要将字段映射为Map,而不想封装成Bean .

默认情况下, Mybatis对Map的解析生成, 如果值(value)为null的话,那么key也不会被加入到map中 .
于是对Map遍历时,key就遍历不到, 因为前端工具的需要,必须有这个key ,网上搜索后发现需要设置  callSettersOnNulls  这个属性.

那就设置呗, 在 sqlSessionFactory 的定义中,指定 configLocation 属性,指向另一个文件,如下所示



解决方法:

转自 : http://blog.csdn.net/lulidaitian/article/details/70941769

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

IFNULL(rate,'') as rate
  • 1

二、ResultType利用实体返回,不用map

三、springMVC+mybatis查询数据,返回resultType=”map”时,如果数据为空的字段,则该字段省略不显示,可以通过添加配置文件,规定查询数据为空是则返回null。

主要是在mybatis的配置文件中添加下面的配置就可以把空的列封装成"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>