springBoot使用Mybatis处理Decimal类型保留两位小数不丢失精度

1.配置Mybatis处理Decimal类型类

@MappedJdbcTypes(JdbcType.DECIMAL)
public class MyBigDecimalTypeHandler extends BigDecimalTypeHandler {

    @Override
    public BigDecimal getNullableResult(ResultSet rs, String columnName) throws SQLException {
        BigDecimal result =super.getNullableResult(rs, columnName)==null?BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP):super.getNullableResult(rs, columnName).setScale(2, BigDecimal.ROUND_HALF_UP);
        return  result;
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return super.getNullableResult(rs, columnIndex)==null?BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP):super.getNullableResult(rs, columnIndex).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return super.getNullableResult(cs, columnIndex)==null?BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP):super.getNullableResult(cs, columnIndex).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}

2.注册

在yml文件配置,此处我用的是mybatis-plus的配置,使用mybatis原生的采用mybatis的type-handlers-package
在这里插入图片描述

3.Springboot中Bigdecimal以json格式返回前端依然丢失小数点

@JsonFormat(shape = JsonFormat.Shape.STRING)
private BigDecimal test;

就是在把数据给前端的时候,把数据转换成string类型,这样就不会丢失小数点后面的(.00)数据。需要注意的是,前端接收到的是string类型数据,如果涉及到数据计算问题,需要前端进行数据转换!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值