使用mybatis查询sql注入到 map 中,唯空字段 也获取出来

环境:node + react +ant 展示数据

    spring + mybatis 查询数据


发现问题:前台输入一个 sql ,后台直接验证sql后数据库查询,将查询到的数据以table的形式前端显示。

某用户通过不同条件获取到的数据字段数不相同,不完整。

查询原因:mybatis 默认情况下,配置文件setting 中有管理这个属性:callSettersOnNulls      版本:3.2 .。默认false,即查询时遇到null 省略该字段。


开启设置

提供两种解决方法:

使用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>

完成。这种方法是设置全局属性,将应用到整个mybatis中。


以下是第二种方式,没有试过不知道能不能正常使用。

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


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值