Use a Formula
(this is an Hibernate specific annotation). From the documentation:
Sometimes, you want the Database to do
some computation for you rather than
in the JVM, you might also create some
kind of virtual column. You can use a
SQL fragment (aka formula) instead of
mapping a property into a column. This
kind of property is read only (its
value is calculated by your formula
fragment).
@Formula("obj_length * obj_height * obj_width")
public long getObjectVolume()
The SQL fragment can be as complex as
you want and even include subselects.
As the documentation writes, the SQL fragment can be pretty complex and can reference the owning entity like in the example below (the non aliased id
column in the o.customer_id=id
part of the where clause references the owning entity column):
@Formula("(select coalesce(extract ('day' from age(max(o.creation_date))), 9999) from Orders o where o.customer_id = id)")
private int daysSinceLastOrder;
See also