java 中映射数据库数值类型时,应优先使用 bigdecimal 来接收 decimal 或 numeric 字段,以彻底避免浮点数精度丢失。在实体类定义中直接指定类型为 java.math.bigdecimal,并在持久层框架(如 mybatis)中配置对应的 jdbc 类型或自动映射规则,确保从 resultset 获取数据时调用 getbigdecimal() 而非 getdouble()。这样能保留原始数据的精确小数位,防止二进制浮点运算带来的舍入误差。

MyBatis 中 BigDecimal 的映射配置方式是什么
在 MyBatis 中,可以通过 resultMap 显式指定列到 BigDecimal 的映射,或者依赖全局的 jdbcTypeForNull 和自动映射机制。对于 DECIMAL 类型,MyBatis 默认通常能正确映射为 BigDecimal,但为了保险起见,建议在 resultMap 中使用 javaType="java.math.BigDecimal" 和 jdbcType="DECIMAL"。此外,若使用 Spring Boot + MyBatis-Plus,需在配置中确保日期和数值类型的处理器正确注册,避免默认处理器将数值转为 Double。

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BigDecimalTypeHandler implements TypeHandler<bigdecimal> {
@Override
public void setParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null) {
ps.setNull(i, Types.DECIMAL);
} else {
ps.setBigDecimal(i, parameter);
}
}
@Override
public BigDecimal getResult(ResultSet rs, String columnName) throws SQLException {
return rs.getBigDecimal(columnName);
}
@Override
public BigDecimal getResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getBigDecimal(columnIndex);
}
@Override
public BigDecimal getResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getBigDecimal(columnIndex);
}
}</bigdecimal>
Hibernate 中如何配置 Decimal 字段的精度与比例
Hibernate 通过 JPA 注解 @Column 的 precision 和 scale 属性来控制 BigDecimal 字段的数据库映射精度。例如,@Column(precision = 10, scale = 2) 表示总位数 10,小数位 2。在实体类中直接使用 BigDecimal 类型,Hibernate 会自动将其映射为数据库的 DECIMAL 或 NUMERIC 类型。若未指定 precision/scale,Hibernate 可能使用默认值(通常为 19,4),这可能导致截断或精度不足。因此,必须根据业务需求显式声明精度,确保存入数据库的值不会因映射配置不当而丢失精度。
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。

import javax.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(precision = 10, scale = 2, nullable = false)
private BigDecimal price;
// getters and setters
}
当数据库返回 NULL 时 BigDecimal 映射会抛出异常吗
当数据库字段为 NULL 时,BigDecimal 映射不会抛出异常,而是返回 Java 中的 null 引用。这是因为 BigDecimal 是对象类型,支持 null 值。在 MyBatis 或 Hibernate 中,若映射目标为基本类型 double 或 float,则可能抛出 SQLException 或返回 NaN,但使用 BigDecimal 可安全处理 NULL。开发者应在代码中对 BigDecimal 进行 null 检查,或使用 Optional 包装,以避免 NullPointerException。这是处理金融或高精度数据时的关键实践。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










