Mybatis自定义TypeHandler

Mybatis是一个优秀的持久层框架,它提供了丰富的功能来简化数据库操作。在Mybatis中,TypeHandler是用于处理Java对象与数据库字段之间的类型转换的组件。自定义TypeHandler可以帮助我们处理一些特殊的数据类型或者自定义的数据类型。

自定义TypeHandler需要实现org.apache.ibatis.type.TypeHandler接口,并重写其中的方法。主要包括以下几个方法:

  1. setParameter:用于将Java对象转换为JDBC参数进行设置。
  2. getResult:用于将数据库字段的值转换为Java对象进行返回。
  3. getResult(CallableStatement cs, int columnIndex):用于将数据库字段的值转换为Java对象进行返回,支持存储过程。
  4. getResult(ResultSet rs, String columnName):用于将数据库字段的值转换为Java对象进行返回,通过字段名获取值。
  5. getResult(ResultSet rs, int columnIndex):用于将数据库字段的值转换为Java对象进行返回,通过字段索引获取值。

下面是一个自定义TypeHandler的示例代码:

java 复制代码
public class MyCustomTypeHandler implements TypeHandler<MyCustomType> {

    @Override
    public void setParameter(PreparedStatement ps, int i, MyCustomType parameter, JdbcType jdbcType) throws SQLException {
        // 将Java对象转换为JDBC参数进行设置
        ps.setString(i, parameter.toString());
    }

    @Override
    public MyCustomType getResult(ResultSet rs, String columnName) throws SQLException {
        // 将数据库字段的值转换为Java对象进行返回
        String value = rs.getString(columnName);
        return new MyCustomType(value);
    }

    @Override
    public MyCustomType getResult(ResultSet rs, int columnIndex) throws SQLException {
        // 将数据库字段的值转换为Java对象进行返回
        String value = rs.getString(columnIndex);
        return new MyCustomType(value);
    }

    @Override
    public MyCustomType getResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 将数据库字段的值转换为Java对象进行返回,支持存储过程
        String value = cs.getString(columnIndex);
        return new MyCustomType(value);
    }
}

在Mybatis的配置文件中,我们需要注册自定义的TypeHandler。可以通过在标签中添加子标签来进行配置,示例如下:

xml 复制代码
<typeHandlers>
    <typeHandler handler="com.example.MyCustomTypeHandler"/>
</typeHandlers>

这样,Mybatis就会在需要处理MyCustomType类型的字段时,使用我们自定义的TypeHandler进行类型转换。

如果项目是使用SpringBoot开发,也可以直接在类配置器的获取sqlSessionFactory实例的方法中进行注入。

其实Mybatis默认提供了一些基本类型的类型转换器,我们可以参照这些类型转换器去自定义。

在这个包目录下:org.apache.ibatis.type

我们随便看一个实现类:BigDecimalTypeHandler

java 复制代码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.apache.ibatis.type;

import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BigDecimalTypeHandler extends BaseTypeHandler<BigDecimal> {
    public BigDecimalTypeHandler() {
    }

    public void setNonNullParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException {
        ps.setBigDecimal(i, parameter);
    }

    public BigDecimal getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getBigDecimal(columnName);
    }

    public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getBigDecimal(columnIndex);
    }

    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getBigDecimal(columnIndex);
    }
}

很简单,就是继承了BaseTypeHandler接口,然后实现其中的抽象方法就可以了。

我们可以自己实现这个BigDecimal的类型转换器,比如我这里自定义了一个BigDecimal类型转换器,默认将查询的结果小数点后面的0去掉。

java 复制代码
package com.au.sa.storeRebate.common.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author xiaohuihui
 * @creteTime 2024-05-01 10:53
 * @description
 */
@Component
public class BigDecimalTypeHandler extends BaseTypeHandler<BigDecimal> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException {
        ps.setBigDecimal(i, parameter);
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getBigDecimal(columnName).stripTrailingZeros();
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getBigDecimal(columnIndex).stripTrailingZeros();
    }

    @Override
    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getBigDecimal(columnIndex).stripTrailingZeros();
    }
}

然后在Mybatis数据源的配置类中,注入Handler的包扫描路径就可以了。

java 复制代码
@Primary
    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("master") DataSource dataSource, @Qualifier("mybatisPlusInterceptor") MybatisPlusInterceptor mybatisPlusInterceptor) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        LOGGER.info("数据库连接池信息:{}", ((HikariDataSource)dataSource).getIdleTimeout());
        GlobalConfig globalConfig=new GlobalConfig();
        globalConfig.setMetaObjectHandler(metaObjectHandler);
        sqlSessionFactory.setGlobalConfig(globalConfig);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        if (Objects.equals(isShowSql, true)) {
            configuration.setLogImpl(StdOutImpl.class);
        }
        configuration.setCacheEnabled(false);
        configuration.addInterceptor(mybatisPlusInterceptor);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        sqlSessionFactory.setTypeHandlersPackage("com.au.sa.storeRebate.common.handler");
        return sqlSessionFactory.getObject();
    }

就是这一行代码:

java 复制代码
sqlSessionFactory.setTypeHandlersPackage("com.au.sa.storeRebate.common.handler");

也可以采用这种形式:

java 复制代码
    @Resource
    private BigDecimalTypeHandler bigDecimalTypeHandler;


    sqlSessionFactory.setTypeHandlers(bigDecimalTypeHandler);

实现的效果:

返回的结果自动将小数点后面的0去除了。

相关推荐
能工智人小辰7 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT8 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄10 分钟前
设计模式之外观模式
java·设计模式·外观模式
知其然亦知其所以然1 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
harmful_sheep1 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵1 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。1 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
nc_kai1 小时前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter
Codebee1 小时前
OneCode:AI时代的先锋——注解驱动技术引领开发范式变革
java
勤奋的知更鸟1 小时前
Java 编程之状态模式
java·开发语言·状态模式