美文网首页
MyBatis自定义TypeHandler

MyBatis自定义TypeHandler

作者: GrooveWind | 来源:发表于2017-03-08 09:41 被阅读0次

    系统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<Sex> {
        @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文件中指定即可:
    <result column="sex" property="sex" typeHandler="xxx.xxx.SexEnumTypeHandler" jdbcType="INTEGER" />
    

    相关文章

      网友评论

          本文标题:MyBatis自定义TypeHandler

          本文链接:https://www.haomeiwen.com/subject/gutbgttx.html