继承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