Search code examples
javahibernateautomapperhibernate-mapping

Setting default values for columns in Hibernate during query mapping


@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?


Solution

  • You have several options:

    1. Use a @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.
    2. Use a @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.
    3. Use an attribute converter if you can leverage JPA 2.1. In this case, you would annotate the field with @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.