MyBatis提供了TypeHandler接口,可以自定义处理Java类型与数据库列类型之间的转换。要使用TypeHandler,需要按照以下步骤操作:
public class MyTypeHandler implements TypeHandler<MyType> {
@Override
public void setParameter(PreparedStatement ps, int i, MyType parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.toString());
}
@Override
public MyType getResult(ResultSet rs, String columnName) throws SQLException {
return MyType.valueOf(rs.getString(columnName));
}
@Override
public MyType getResult(ResultSet rs, int columnIndex) throws SQLException {
return MyType.valueOf(rs.getString(columnIndex));
}
@Override
public MyType getResult(CallableStatement cs, int columnIndex) throws SQLException {
return MyType.valueOf(cs.getString(columnIndex));
}
}
<typeHandlers>
<typeHandler handler="com.example.MyTypeHandler"/>
</typeHandlers>
@Results({
@Result(property = "myField", column = "my_column", javaType = MyType.class, typeHandler = MyTypeHandler.class)
})
这样,在查询结果映射时,MyBatis会自动调用MyTypeHandler来处理MyType类型的数据与数据库列类型之间的转换。