Mybatis解决空字符串保存入Mysql数字字段的类型转换问题

    我们在使用Mysql的过程中,经常会碰到无法将空字符串写入数字字段的问题。下面我将用Mybatis的类型处理器特性来解决这个问题。首先创建类型处理器类。

    package com.newpage.common.util; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import com.newpage.common.base.NewFunc; public class NewpageTypeHandler implements TypeHandler { public Object getResult(ResultSet rs, String columnName) throws SQLException { return rs.getString(columnName); } public Object getResult(CallableStatement cs, int columnIndex) throws SQLException { return cs.getString(columnIndex); } public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { String param = NewFunc.getInstance().ObjectToStr(parameter); if(!NewFunc.getInstance().ChkEmpty(param)) { param = null; } ps.setString(i, param); } }

 

接着将类型处理器配置到Mybatis的配置文件中

 

这样就完成了我们保存Mysql空字符串的问题了。同样也可以修改上面的处理器,对字段进行缺省值的设置。

你可能感兴趣的:(Mybatis)