MyBatis自定义类型转换器
MyBatis自定义将java对象中的boolean转换为数据库数据类型numeric
将java实体Boolean类型flag属性值在插入数据库时转换为0(false),1(true)
自定义类型转换器实现TypeHandler类型转换接口
public class MyTypeHandler implements TypeHandler{
/**
* 生成sql语句时被调用
*
* @PreparedStatement 准备创建的参数对象
* @i 当前占位符所在的位置
* @parameter 占位符所关联的数据
*
*/
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
if(parameter==null){
ps.setInt(i, 0);
}
Boolean flag=(Boolean)parameter;
if(flag==true){
ps.setInt(i, 1);
}else{
ps.setInt(i, 0);
}
}
/**
* 查询结束后将ResultSet数据行转换封装为实体对象时调时,通知TypeHandler将当前数据行的某个字段转换为何种类型
*
* @rs 当前遍历的数据行
* @columnName 字段值
*/
public Object getResult(ResultSet rs, String columnName) throws SQLException {
int flag=rs.getInt(columnName);
Boolean myFlag=Boolean.FALSE;
if(flag==1){
return myFlag=Boolean.TRUE;
}
return myFlag;
}
public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
在MyBatis配置文件中添加typeHandlers标签
<typeHandlers>
<typeHandlers handler='com.song.util.MyTypeHandler' javaType='Boolean' jdbcType='NUMERIC'/>
</typeHandlers>
注意标签位置,不然编译报错