使用JPA / Hibernate计算属性 [英] Calculated property with JPA / Hibernate
问题描述
COUNT()
函数进行计算。如果这个属性可以根据需求/懒惰地计算,那就更好了,但这不是强制性的。在最坏的情况下,我可以设置这个bean的属性与HQL或Criteria API,但我不希望。 Hibernate @Formula
注释可能有帮助,但我几乎找不到任何文档。
非常感谢任何帮助。谢谢。JPA不提供对派生属性的任何支持,所以你将不得不使用提供者特定的扩展。
正如你所提到的,当使用Hibernate时, @Formula
对于这是完美的。您可以使用SQL片段: @Formula(PRICE * 1.155)
private float finalPrice;
甚至可以在其他表格上进行复杂查询:
< pre $ @Formula((从订单中选择min(o.creation_date)o o.customer_id = id))
private日期firstOrderDate;
其中 id
是 id
。
以下博客文章值得一读: Hibernate派生属性 - 性能和可移植性。
没有更多细节,我可以我不能给出更准确的答案,但上面的链接应该是有帮助的。
另见:
- 部分 5.1。 22。列和公式元素(Hibernate核心文档)
- 部分 2.4.3.1。公式(Hibernate注释文档)
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 COUNT()
function operating on the join of my Java bean and its children. It would be even better if this property could be calculated on demand / "lazily", but this is not mandatory.
In the worst case scenario, I can set this bean's property with HQL or the Criteria API, but I would prefer not to.
The Hibernate @Formula
annotation may help, but I could barely find any documentation.
Any help greatly appreciated. Thanks.
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;
Where 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.
See also:
- Section 5.1.22. Column and formula elements (Hibernate Core documentation)
- Section 2.4.3.1. Formula (Hibernate Annotations documentation)
这篇关于使用JPA / Hibernate计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!