Search code examples
mysqljpajbossejbinfinity

Storing Double.POSITIVE_INFINITY in MySQL (EJB entity/JBoss)


I have the following simple JPA entity:

@Entity
@Table( name = myentity_table )
public class MyEntity {

  private double a;
  private double b;
  //(...)
}

a and b may be set to Double.POSITIVE_INFINITY. When I try to store entity with double set to +INF into database (MySQL) using standard entity manager I get exception:

java.sql.SQLException: 'Infinity' is not a valid numeric or approximate numeric value

As far as I know MySQL may not support NaN/-INF/+INF numbers. Is there any way to store this entity without writing HQL queries and translating +INF into null (or max double) ? Ideally, I'd like to do it via entity manager as usual.

Thanks in advance.


Solution

  • Entity life-cycle callback methods @PrePersist, @PreUpdate can be used here to verify the field value NAN/-INF/+INF etc & then setting the default value accordingly.

     //--
    
     @PrePersist  
     @PreUpdate  
     private void resetField() {
    
          if(field == Double.POSITIVE_INFINITY)
                field = somePredefinedValue;
     }
    
     //--