使用JPA / Hibernate计算属性 [英] Calculated property with JPA / Hibernate

查看:102
本文介绍了使用JPA / Hibernate计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java bean有一个childCount属性。此属性未映射到数据库列。相反,应该由数据库计算,通过在我的Java bean及其子项的连接上操作的 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派生属性 - 性能和可移植性



没有更多细节,我可以我不能给出更准确的答案,但上面的链接应该是有帮助的。

另见:




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:

这篇关于使用JPA / Hibernate计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆