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
  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot和MyBatis Plus一起使用时,可以使用TypeHandler来处理数据库中的自定义类型和Java对象之间转换。 首先,您需要创建一个自定义的TypeHandler类来处理特定类型的转换。例如,假设您有一个名为CustomType的自定义类型,您可以创建一个CustomTypeHandler类来处理它的转换。 ```java 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 CustomTypeHandler extends BaseTypeHandler<CustomType> { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, CustomType customType, JdbcType jdbcType) throws SQLException { preparedStatement.setString(i, customType.toString()); } @Override public CustomType getNullableResult(ResultSet resultSet, String s) throws SQLException { return CustomType.fromString(resultSet.getString(s)); } @Override public CustomType getNullableResult(ResultSet resultSet, int i) throws SQLException { return CustomType.fromString(resultSet.getString(i)); } @Override public CustomType getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return CustomType.fromString(callableStatement.getString(i)); } } ``` 在这个例子中,CustomTypeHandler继承自MyBatis中的BaseTypeHandler,并重写了一些方法来实现类型转换。setNonNullParameter方法用于将Java对象转换数据库中的值,getNullableResult方法用于将数据库中的值转换为Java对象。 接下来,在您的实体类中使用@TableField注解来指定字段使用自定义的TypeHandler。例如: ```java public class MyEntity { @TableField(typeHandler = CustomTypeHandler.class) private CustomType customType; // 其他字段和方法... } ``` 最后,您需要在MyBatis的配置文件中注册自定义的TypeHandler。在application.properties或application.yml中添加以下配置: ```yaml mybatis-plus: configuration: map-underscore-to-camel-case: true type-handlers-package: com.example.typehandler ``` 这里的`com.example.typehandler`是您自定义TypeHandler类的包路径。 通过这些步骤,您就可以在Spring Boot中使用MyBatis Plus的TypeHandler来处理自定义类型和Java对象之间转换了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值