我可以在 Spring Data JPA 中将 NaN 处理为 NULL 吗?

Can I handle NaN as NULL in Spring Data JPA?

我的 Postgres 数据库中有一些包含 NaN 值的列。我们正在处理资金,所以我所有的实体都是 BigDecimals,它不能容纳 NaN。

在 JPA 或 Hibernate 上是否有设置或其他东西,我可以告诉它“将任何 NaN 视为 NULLS”

您可以使用 @ColumnTransformer 对单个列执行此操作,也可以通过 MetadataContributor 以编程方式执行此操作(请参阅 How to provide read and write to ColumnTransofrmer programatically in Hibernate?),但无法全局执行此操作。

但是,如果您的数据库中有 NaN,则说明已经有问题了,因为您正在使用某种 float/double 类型保存值。所以 IMO 你应该首先迁移数据 update tbl set col = null where is_nan(col) 然后切换到 alter table tbl alter column col set datatype numeric(19,3) 或类似的东西。