项目中使用MyBatis查询数据库,数据库中一个字段的值有一部分是null,想给这些null值指定一个默认值。
实现的方式是重写TypeHandler:
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
String value = rs.getString(columnName);
if (value == null) {
return "姓名为空";
}
return value;
}
xml配置:
<resultMap id="userMap" type="mybatis.domain.Users">
<id property="id" column="id"/>
<result property="userName" column="user_name" typeHandler="mybatis.handler.MyStringTypeHandler"/>
<result property="sex" column="sex"/>
</resultMap>
但是返回的字段仍然是null,跟踪下源码:
if (rs.wasNull()) {
return null;
} else {
return result;
}
原因是BaseTypeHandler中的这块代码影响的,rs.wasNull
的值为true
。
如何才能使null值得字段返回指定的默认值呢?
抽象类org.apache.ibatis.type.BaseTypeHandler的几个getResult()方法是public的, 你重新一下这几个方法不就好了吗?
举个例子: