MyBatis自定义TypeHandler

系统TypeHandler

  • MyBatis为Java类型和相应的JDBC类型提供了系统默认的typeHandler,并且已经注册好:
public TypeHandlerRegistry() {
    register(Boolean.class, new BooleanTypeHandler());
    register(boolean.class, new BooleanTypeHandler());
    register(JdbcType.BOOLEAN, new BooleanTypeHandler());
    ......
    register(Character.class, new CharacterTypeHandler());
    register(char.class, new CharacterTypeHandler());
}

自定义TypeHandler

  • 当系统注册的typeHandler不满足我们的需求时(如使用枚举的时候),可以通过实现org.apache.ibatis.type.TypeHandler接口来进行扩展,以达到我们自己控制类属性与数据库字段映射的目的,具体实现如下:
public class SexEnumTypeHandler implements TypeHandler {
    @Override
    public void setParameter(PreparedStatement ps, int idx, Sex sex, JdbcType jdbcType) throws SQLException {
        ps.setInt(idx, sex.getCode());
    }
    @Override
    public Sex getResult(ResultSet rs, String columnName) throws SQLException {
        int code = rs.getInt(columnName);
        return Sex.getSex(code);
    }
    @Override
    public Sex getResult(ResultSet rs, int columnIndex) throws SQLException {
        int code = rs.getInt(columnIndex);
        return Sex.getSex(code);
    }
    @Override
    public Sex getResult(CallableStatement cs, int columnIndex) throws SQLException {
        int code = cs.getInt(columnIndex);
        return Sex.getSex(code);
    }
}

其中Sex是一个自定义的枚举:

public enum Sex {
    UNKNOWN(-1, "未知"),
    MALE(0, "男"),
    FEMALE(1, "女"),
    ;
    private int code;
    private String name;
    private Sex(int code, String name) {
        this.code = code;
        this.name = name;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
  • 定义好之后,在相应的mapper文件中指定即可:

你可能感兴趣的:(MyBatis自定义TypeHandler)