Home >Java >javaTutorial >How Can I Map Calculated Properties in JPA and Hibernate Without Using HQL or Criteria API?
Mapping Calculated Properties with JPA and Hibernate
Background:
Suppose you have a Java bean with a property that is not mapped to a database column directly. Instead, you want it calculated by the database using an operation like COUNT(). You seek a way to map this property without resorting to HQL or the Criteria API.
Solution Using Hibernate's @Formula:
JPA does not directly support derived properties. However, Hibernate provides the @Formula annotation as a solution. Using this annotation, you can specify a formula for the property, which can include SQL fragments or complex queries:
@Formula("COUNT(childColumns)") private int childCount;
Example Formulas:
@Formula("PRICE*1.155") private float finalPrice;
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)") private Date firstOrderDate;
Benefits of @Formula:
Additional Resources:
The above is the detailed content of How Can I Map Calculated Properties in JPA and Hibernate Without Using HQL or Criteria API?. For more information, please follow other related articles on the PHP Chinese website!