@Column (name="AMOUNT")
private BigDecimal amount;
I saw many answers in Stackoverflow, the solution is either using columnDefinition
or set the default value in Java contructor.
But what I need is for data query, not table creation or data insertion. When I use hibernate session to query out the object, and call the method getAmount()
, it will return null BigDecimal
Object, which I want to set the default value to 0 BigDecimal
.
How can I do that since the mapping is done by Hibernate framework?
You have several options:
@Transient
getter method. In this case, you may want to mark the getter for the amount field as protected or private (Hibernate won't care) and then expose a special public method that is annotated with @Transient
that performs the translation for you.@PostLoad
annotated method event callback to translate the value rather than a @Convert
. You'd likely want to leverage part of #1 where you add a new property that stores the translated value you calculate in the post load callback and then annotate the field or getter with @Transient
.@Convert
and specify a converter class implementation that translates a null value to 0
. The benefit of the first two options is that you don't need to be concerned with how to map values back to the database column (e.g. does 0
translate to a NULL
at the table level).
From a performance perspective, if amount
is accessed numerous times, I'd probably use #2 personally and cache the value after having translated it once.