My Java bean has a childCount property. This property is not mapped to a database column. Instead, it should be calculated by the database with a
In the worst case scenario, I can set this bean's property with HQL or the Criteria API, but I would prefer not to.
JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned,
@Formula is perfect for this when using Hibernate. You can use an SQL fragment:
@Formula("PRICE*1.155") private float finalPrice;
Or even complex queries on other tables:
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)") private Date firstOrderDate;
id is the
id of the current entity.
The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.
Without more details, I can't give a more precise answer but the above link should be helpful.