问题描述
我的Java bean具有childCount属性.此属性未映射到数据库列.相反,应该由数据库使用COUNT()
函数来对它进行计算,该函数对我的Java bean及其子级的联接进行操作.如果可以按需/懒惰地"计算此属性,那就更好了,但这不是强制性的.
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.
在最坏的情况下,我可以使用HQL或Criteria API设置此bean的属性,但我不希望这样做.
In the worst case scenario, I can set this bean's property with HQL or the Criteria API, but I would prefer not to.
Hibernate @Formula
批注可能会有所帮助,但我几乎找不到任何文档.
The Hibernate @Formula
annotation may help, but I could barely find any documentation.
任何帮助,我们将不胜感激.谢谢.
Any help greatly appreciated. Thanks.
推荐答案
JPA不提供对派生属性的任何支持,因此您必须使用提供程序特定的扩展.正如您提到的,使用Hibernate时@Formula
对此非常适合.您可以使用一个SQL片段:
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
是当前实体的id
.
以下博客文章值得一读:休眠派生属性-性能和可移植性.
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.
- 第 5.1.22.列和公式元素(Hibernate Core文档)
- 第 2.4.3.1节.公式(休眠注释文档)
- Section 5.1.22. Column and formula elements (Hibernate Core documentation)
- Section 2.4.3.1. Formula (Hibernate Annotations documentation)
这篇关于如何使用JPA和Hibernate映射计算的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!