• MyBatis-TypeHandler(数据类型转换)


    TypeHandler是什么

    • TypeHandler被称作类型处理器,无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时,都会用类型处理器将获取的值以合适的方式转换成 Java 类型。Mybatis默认为我们实现了许多TypeHandler, 当我们没有配置指定TypeHandler时,Mybatis会根据参数或者返回结果的不同,默认为我们选择合适的TypeHandler处理。
    Type HandlerJava TypesJDBC Types
    BooleanTypeHandlerjava.lang.Boolean, booleanAny compatible BOOLEAN
    ShortTypeHandlerjava.lang.Short, shortAny compatible NUMERIC or SHORT INTEGER
    StringTypeHandlerjava.lang.StringCHAR, VARCHAR
    详细可见org.apache.ibatis.type包下内容

    自定义一个TypeHandler

    1. 创建一个类,继承BaseTypeHandler或者实现TypeHandler
    • 继承BaseTypeHandler
    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    import org.apache.ibatis.type.MappedJdbcTypes;
    import org.apache.ibatis.type.MappedTypes;
    
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    /**
     * author: boo
     */
    @MappedTypes({String.class})
    //@MappedJdbcTypes(JdbcType.VARCHAR)
    public class AESEncryptHandler extends BaseTypeHandler<String>{
    
        /** 将parameter转换成对应的数据库类型 */
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
            ps.setString(i, AES.encrypt(parameter));
        }
    
        /** 根据字段名获取从数据库读取的字段数据 */
        @Override
        public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
            String columnValue = rs.getString(columnName);
            return AES.decrypt(columnValue);
        }
    
    
        @Override
        public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
            String columnValue = rs.getString(columnIndex);
            return AES.decrypt(columnValue);
        }
    
        /** 根据下标获取从数据库读取的字段数据 */
        @Override
        public String getNullableResult(CallableStatement cs, int columnIndex)
                throws SQLException {
            String columnValue = cs.getString(columnIndex);
            return AES.decrypt(columnValue);
        }
    
        public AESEncryptHandler() {
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    以上为自定义的一个TypeHandler,作用是对一些数据库的敏感字段进行加密处理;
    其中 AES.encrypt(String str)是自定义的一个字符串加密方法,这里可以根据自己的需求实现

    • 实现TypeHandler接口的方法与上类似,不作赘述
    2. 自定义TypeHandler的使用
    • TypeHandler的使用方式有两种,全局注册使用,或指定字段使用
    2.1 全局注册使用

    有三种方式可以进行全局注册

      1. xml定义
    <typeHandlers>          
    	<typeHandler handler="com.boo.mybatis.demo.convert.AESEncryptHandler "/> 
    typeHandlers>
    
    • 1
    • 2
    • 3
      1. java config注入
    @Configuration
    public class MyBatisConfig
    {
        ......
        ......
    
        @Bean
        public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
        {
            String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage");
            String mapperLocations = env.getProperty("mybatis.mapperLocations");
            String configLocation = env.getProperty("mybatis.configLocation");
            typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
            VFS.addImplClass(SpringBootVFS.class);
    
            final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(...);
            // 自定义TypeHandler所在包
    //        sessionFactory.setTypeHandlersPackage("com.ruoyi.common.convert");
    		// 指定注册单个或多个TypeHandler
    		sessionFactory.setTypeHandlers(new TypeHandler[]{new AESEncryptHandler()});
            sessionFactory.setTypeAliasesPackage(...);
            sessionFactory.setMapperLocations(...);
            sessionFactory.setConfigLocation(...);
            return sessionFactory.getObject();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
      1. @Annotation(注解)
  • 相关阅读:
    C# 泛型
    ansible playbook实现磁盘格式化及文件系统挂载
    第十五届蓝桥杯模拟赛【第三期】Java
    Python Gui之tkinter(下)
    go sync.Map包装过的对象nil值的判断
    Golang | Leetcode Golang题解之第50题Pow(x,n)
    阿里云OSS依赖无法导入的问题
    如何创建自己的小程序?
    2022合肥站 G-Game Plan
    关于父母离婚后子女姓名变更有关问题的批复
  • 原文地址:https://blog.csdn.net/HELLOMRP/article/details/114321615