问题描述
我的 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 不提供对派生属性的任何支持,因此您必须使用提供者特定的扩展.正如您所提到的,@Formula
在使用 Hibernate 时非常适合于此.您可以使用 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
.
以下博客文章值得一读:Hibernate 派生属性 - 性能和便携性.
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.公式(Hibernate Annotations 文档)
- Section 5.1.22. Column and formula elements (Hibernate Core documentation)
- Section 2.4.3.1. Formula (Hibernate Annotations documentation)
这篇关于如何使用 JPA 和 Hibernate 映射计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!