在数据库中存储Double.POSITIVE_INFINITY(EJB实体/ JBoss)

| 我有以下简单的JPA实体:
@Entity
@Table( name = myentity_table )
public class MyEntity {

  private double a;
  private double b;
  //(...)
}
a和b可以设置为
Double.POSITIVE_INFINITY
。当我尝试使用标准实体管理器将双重设置为+ INF的实体存储到数据库(MySQL)中时,出现异常:   java.sql.SQLException:\'Infinity \'不是有效的数字或近似数字值 据我所知,MySQL可能不支持NaN / -INF / + INF编号。有什么方法可以存储该实体而无需编写HQL查询并将+ INF转换为null(或max double)?理想情况下,我希望像往常一样通过实体管理器来执行此操作。 提前致谢。     
已邀请:
实体生命周期回调方法@ PrePersist,@ PreUpdate可在此处用于验证字段值NAN / -INF / + INF等,然后相应地设置默认值。
 //--

 @PrePersist  
 @PreUpdate  
 private void resetField() {

      if(field == Double.POSITIVE_INFINITY)
            field = somePredefinedValue;
 }

 //--
    
MySQL似乎不支持\“ infinity \”。本文写道:   通过插入任意大的负数可以在MySQL数据库中存储和检索负无穷大。 肯定也是一样。其他资源也使用
1e500
。 建议您不要使用
Float.MAX_VALUE
Float.MIN_VALUE
(或
Double
等效项),而不要使用无穷大 如果在设置值时无法在代码中执行此操作,请按照建议的ѭ7进行操作。     
我通过添加一个varchar列来存储
Float.NaN
Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY
的文本表示来解决此问题,而原始列将存储
NULL
。 然后,我使用setter和getter来管理这两列。 在我的@Entity类中
/** The value I persist. See it is a Float; */
@Column(name = \"VALUE\")
private Float value;

/** the \'value complement\' that does the trick. */
@Column(name = \"VALUE_COMPLEMENT\") // You can see I\'ve added a new column in my table (it is a varchar)
private String valueComplement;

/**
 * value getter.
 * If my value is null, it could mean that it is a NaN or +/- infinity.
 * Then let\'s check the complement.
 */
public Float getValue() {
    if (value == null) {
        try {
            return Float.parseFloat(this.valueComplement);
        } catch (NumberFormatException e) {
            return null;
        }
    } else {
        return value;
    }
}

/**
 * value setter
 * If the given value is a NaN or Inf, set this.value to null 
 * and this.complement to the string representation of NaN or +/- Inf.
 */
public void setValue(Float value) {
    if (value != null && (value.isNaN() || value.isInfinite())) {
        this.valueComplement = value.toString();
        this.value = null;
    } else {
        this.value = value;
    }
}
结果:
| ID | LABEL                 | VALUE | VALUE_COMPLEMENT |
| -- | --------------------- | ----- | ---------------- |
|  1 | PI                    |  3.14 | NULL             |
|  2 | gravity acceleration  |  9.81 | NULL             |
|  3 | sqare root of -1      | NULL  | NaN              |
|  4 | log of 0              | NULL  | -Infinity        |
    

要回复问题请先登录注册