user1712638
user1712638

Reputation: 317

Float primitive to return null if possible or a specific value if the value is null in the DB

So basically as the title mentions this is what I'm trying to do, I have this column defined

@Column(name="MATCH_SCORE", columnDefinition="NUMBER(10,4) default '-1.0000'")
private float matchScore;

so what I was expecting is that value to return with -1 if it's null in the DB, however, I still get it as 0 which is an issue because I have to take a specific action if the value is zero while I don't do it in case the value is null, unfortunately, I can't do any change the DB, so I'll have to do it from the app side.

Cheers.

Upvotes: 0

Views: 490

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109595

If you want to use the primitive type float, instead of the nullable BigDecimal that also has no rounding problems, do

@Column(name="MATCH_SCORE", columnDefinition="NUMBER(10,4)")
private Float matchScoreRaw;

@Transient
public float getMatchScore() {
    return matchScoreRaw == null ? Float.NaN : matchScoreRaw;
}

@Deprecated
public Float getMatchScoreRaw() {
    return matchScoreRaw == null ? Float.NaN : matchScoreRaw; // Bad.
}

Representing dataabase NULL as not-a-number. A getter for the raw value might help "repairing" the database, though NULL might be better, as I do not know how NaN is represented in the database, and whether it can be read again.

Best would be to convert all NULL entries to something and not use two fields.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522074

Part of the problem here might be that primitive float cannot be null. Instead, you could use Float, but a better choice to map a NUMBER (exact precision) column would be BigDecimal. Try this version:

@Column(name="MATCH_SCORE", columnDefinition="NUMBER(10,4) default -1.0000")
private BigDecimal matchScore;

Also note that the purpose of a column's default value is that if an insert happens and no value (or NULL) is specified for that column, then the database will use that default value instead. Default values don't really have anything to do with what happens when you select; whatever value is in the column for that record will be returned.

Upvotes: 2

Related Questions