mybatis之TypeHandler,再也不怕数据库与实体类之间的数据转换问题了

TypeHandler

  • 类型处理器的基类,MyBatis 中的 TypeHandler 类型处理器用于 JavaType 与 JdbcType 之间的转换;
  • 用于PreparedStatement 设置参数值和从 ResultSet 或 CallableStatement 中取出一个值;
  • MyBatis 内置了很多TypeHandler;

可以实现BaseTypeHandler,自定义 TypeHandler。

示例(数据类型转换,解决科学计数法问题)

通常我们在使用BigDecimal的时候,从数据库中查询出来,由于将计算机的运算方式,太大的数会被转换成科学计数法来显示
那么我们就可以借助TypeHandler来解决了,简而言之就是在数据进出数据库之前,对其进行转换
那么,这里有两种方式,一种是局部解决,一种是全局解决问题,针对不同需求场景,选择不同的方式即可。

局部自定义方式

首先需要我们自定义一个处理类来手动处理,继承BaseTypeHandler即可。

  • @MappedTypes :指定与其关联的 Java 类型列表。 如果在 javaType 属性中也同时指定,则注解上的配置将被忽略,例:@MappedJdbcTypes(JdbcType.INTEGER)。
  • @MappedJdbcTypes :指定与其关联的 JDBC 类型列表。 如果在jdbcType
    属性中也同时指定,则注解上的配置将被忽略。
@MappedTypes(BigDecimal.class)
public class CustomBigDecimalHandler 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 toPlainStringBigDecimal(rs.getBigDecimal(columnName));
    }
	//通过列索引
    @Override
    public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toPlainStringBigDecimal(rs.getBigDecimal(columnIndex));
    }

	//针对存储过程
    @Override
    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toPlainStringBigDecimal(cs.getBigDecimal(columnIndex));
    }
	
    private BigDecimal toPlainStringBigDecimal(BigDecimal decimal) {
        if(decimal != null) {
            return new BigDecimal(decimal.toPlainString());
        }
        return null;
    }
}

创建实体类

@Data
@TableName(value = "wage",autoResultMap = true)
public class Wage {
    @TableId("ID")
    private String id;

    @TableField(value = "MONEY",typeHandler = CustomBigDecimalHandler.class)
    private String money;
 }

当然,这样注解方式只适合你使用mybatis-plus自带的查询,如果是xml写的语句,那么你需要这样做即可;

<!--查询  -->
<resultMap id="wageMapperResultMap" type="org.spring.springboot.entity.Wage">
      <result column="id" jdbcType="INTEGER" property="id"></result>
      <result column="money" jdbcType="Decimal" property="MONEY" typeHandler="org.spring.springboot.config.CustomBigDecimalHandler"></result>
   </resultMap>
<select id="selectWageById" resultMap="wageMapperResultMap">
      select * from Wage where id = #{id}
   </select>
   
   <!--插入  -->
   <insert id="insertWage" parameterType="org.spring.springboot.entity.Wage"> 
      insert into student (id,name,course,score)  values
      <foreach collection="list" item="wage" separator=",">
         (#{student.id},#{wage.money,typeHandler=org.spring.springboot.config.CustomBigDecimalHandler}) 
      </foreach>
   </insert>

全局方式

如果你想针对某个类型的字段进行处理且全局生效,那么也有就几种方式:

  • 配置类
@Slf4j
@Configuration
@ComponentScan("boot")
@MapperScan(basePackages = {"boot.*.mapper", "boot.mapper"})
public class MybatisPlusConfig {
@Bean(name = "sqlSessionFactorySystem")
    public SqlSessionFactory sqlSessionFactoryOne(@Qualifier("dataSourceSystem") DataSource dataSource) throws Exception {
        return createSqlSessionFactory(dataSource);
    }
public SqlSessionFactory createSqlSessionFactory(DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //全局配置
        //GlobalConfig globalConfig = new GlobalConfig();
        //配置填充器
        //globalConfig.setMetaObjectHandler(new MybatisPlusMetaObjectHandler());
        //bean.setGlobalConfig(globalConfig);
        bean.setTypeHandlers(new CustomBigDecimalHandler());
        return bean.getObject();
    }
}
  • xml配置
    在mybatis-config.xml配置指定的typeHandler类
<configuration>
    <typeHandlers>
        <typeHandler handler="com.xxx.typehandler.CustomBigDecimalHandler"/>
    </typeHandlers>
</configuration>
  • 配置文件
    这种网上有的说可以,但我的项目试了,但是不管用,不知道原因。
mybatis-plus:
  type-handlers-package: jnpf.config
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值