需求:将数据库为空的字段赋默认值
解决办法:
第一步:为空便被结果集舍弃时mybatis操作的,这个默认的配置可以取消
在mybatis配置文件中加入setting
<settings>
<setting name="callSettersOnNulls" value="true"/>
</settings>
第二步:写一个类继承TypeHandler<String>
接口,这个接口封装了返回结果集格式
package com.example.demo.config;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StringIsNull 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 { }
}
第三步:mybatis返回结果格式进行设置,设置为自己写的类
<select id="getDept" resultMap="dept">
select
t.dept_code "id",
t.simplename "name",
t.parent_dept_code "parentid"
from dd_dept t
</select>
<resultMap id="dept" type="java.util.HashMap">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="parentid" column="parentid" typeHandler="com.example.demo.config.StringIsNull"/>
</resultMap>
因为部门可能为空,所以单独设置部门字段的typeHandler为StringIsNull类
即可解决问题