Mybatis使用TypeHandler实现Java类型与数据库类型的自定义转换

TypeHandler

当 SpringBoot 项目中使用到Mybatis时,通常情况下程序中使用的各种基本数据类型在数据库中都有定义,如 String - VARCHAR;
但当使用一些数据库中没有定义的数据类型时,如 Serializable ,此时 Mybatis 无法在数据库的数据类型和程序中的数据类型之间进行转换,就需要使用到自定义 TypeHandler;

通过实现 BaseTypeHandler<需要转换的Java类型> 来自定义类型的转换

举例将 Java 中的 Serializable 转换为 数据库中的 BIGINT

@MappedTypes(Serializable.class)
@MappedJdbcTypes(JdbcType.BIGINT)
public class SerializableTypeHandler extends BaseTypeHandler<Serializable> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Serializable parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter, JdbcType.BIGINT.TYPE_CODE);
    }

    @Override
    public Serializable getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long result = rs.getLong(columnName);
        return result == 0 && rs.wasNull() ? null : result;
    }

    @Override
    public Serializable getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long result = rs.getLong(columnIndex);
        return result == 0 && rs.wasNull() ? null : result;
    }

    @Override
    public Serializable getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long result = cs.getLong(columnIndex);
        return result == 0 && cs.wasNull() ? null : result;
    }
}

在程序启动时需要向Mybatis的TypeHandlerRegistry中注册自定义的TypeHandler

SpringBoot注册示例:

public class Test implements ApplicationContextAware {
    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(Test.class, args);
        SpringBeanLoader.setApplicationContext(applicationContext);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SqlSessionTemplate bean = applicationContext.getBean(SqlSessionTemplate.class);
        Configuration configuration = bean.getConfiguration();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        typeHandlerRegistry.register(SerializableTypeHandler.class);
    }
}

同时,需要定义数据库类型转回Java数据类型

此时需要在使用到该属性的mapper文件中通过resultMap定义:

	    <resultMap id="BASE_RESULTMAP" type="***.entity.Test">
        	<id column="test_id" property="id" typeHandler="***.handler.SerializableTypeHandler"/>
    	    <result column="test_name" jdbcType="VARCHAR" property="name"/>
        resultMap>

你可能感兴趣的:(MyBatis,java)