mybatis typehandler使用详解

在微服务架构中,MyBatis 是一种流行的持久层框架,它提供了强大的数据访问功能,同时与Spring Boot等微服务技术栈无缝集成。MyBatis 的 TypeHandler 是一个重要的特性,它负责 Java 类型和数据库类型之间的映射,使得开发者可以自定义如何在 Java 对象和数据库类型之间转换数据。

使用场景

TypeHandler 最常见的使用场景包括:

  • 处理 Java 中不存在的数据库特定类型。
  • 对某些数据类型进行加密和解密。
  • 实现枚举类型与数据库中字符串或整数的映射。
  • 处理 Java 日期和时间类型与数据库日期和时间类型的转换。

实现 TypeHandler

要自定义类型处理器,需要实现 MyBatis 提供的 TypeHandler 接口或继承一个便捷的基类 BaseTypeHandler。以下是自定义 TypeHandler 的一般步骤:

步骤 1:创建 TypeHandler 类

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MyCustomTypeHandler extends BaseTypeHandler {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, 
                                    CustomJavaType parameter, JdbcType jdbcType) throws SQLException {
        // Java 类型 => 数据库类型
        ps.setString(i, parameter.toString());
    }

    @Override
    public CustomJavaType getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 数据库类型 => Java 类型
        return new CustomJavaType(rs.getString(columnName));
    }

    @Override
    public CustomJavaType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return new CustomJavaType(rs.getString(columnIndex));
    }

    @Override
    public CustomJavaType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return new CustomJavaType(cs.getString(columnIndex));
    }
}

步骤 2:注册 TypeHandler

在 MyBatis 配置文件中注册自定义的 TypeHandler


    

或者在 Mybatis 配置类中注册:

@MapperScan("com.example.mapper")
@Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.getTypeHandlerRegistry().register(MyCustomTypeHandler.class);
    }
}

步骤 3:使用 TypeHandler

在 MyBatis Mapper XML 文件或注解中显式使用 TypeHandler



或者在 Java Mapper 接口中使用注解形式指定:

@Select("SELECT column FROM table WHERE other_column = #{value}")
@Results({
    @Result(column="column", property="propertyInJavaObject", typeHandler=MyCustomTypeHandler.class)
})
CustomJavaType selectByExample(CustomJavaType value);

你可能感兴趣的:(mybatis)