Mybatis使用TypeHandler解决读写数据库栏位null问题

继承BaseTypeHandler并重写几个方法:

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({String.class})
public class MyStringTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i,s);
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {

        return resultSet.getString(s)==null?"test2":resultSet.getString(s);

    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return resultSet.getString(i)==null?"test3":resultSet.getString(i);
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            if (jdbcType == null) {
                throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
            }

            try {
                this.setNonNullParameter(ps, i, "not null!!!", jdbcType);
            } catch (SQLException var7) {
                throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: " + var7, var7);
            }
        } else {
            try {
                this.setNonNullParameter(ps, i, parameter, jdbcType);
            } catch (Exception var6) {
                throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . Try setting a different JdbcType for this parameter or a different configuration property. Cause: " + var6, var6);
            }
        }

    }

1.setParameter 方法用于对String类型的null属性转换为指定的字符串"not null!!!"
2.getNullableResult的三个方法用于对数据库中读取到的null值转为需要的字符串(test3)等
3.SQL语句部分:

(关键)

插入语句的sql中一定要指明每个sql语句的jdbcType 否则将会使用BaseTypehandler转换字段值

<insert id="insertList" >
        insert into db01.${tableName} (book_name, isdn, public_date, author) values
        <foreach collection="list" item="item" separator=",">
            (#{item.bookName,jdbcType=VARCHAR},
             #{item.isdn,jdbcType=NUMERIC},
             #{item.publicDate,jdbcType=TIMESTAMP},
             #{item.author,jdbcType=VARCHAR})
        </foreach>
    </insert
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值