使用JPA映射计算的属性 [英] Mapping calculated properties with JPA
问题描述
有没有办法使用JPA映射计算属性?
Is there a way to map a calculated property using JPA?
假设我有一个 Invoice
对象其中有一个或多个 InvoiceLineItems
,我想在 Invoice
类上有一个持久的计算属性,它给了我总数金额:
Assuming I have an Invoice
object with one or more InvoiceLineItems
within it, I want to have a persistent calculated property on the Invoice
class that gives me the total amount:
class Invoice {
...
@Column(name = "TOTAL_AMOUNT")
public BigDecimal getTotalAmount() {
BigDecimal amount = BigDecimal.ZERO;
for (InvoiceLineItem lineItem : lineItems) {
amount = amount.add(lineItem.getTotalAmount());
}
return amount;
}
}
现在,我可以创建一个受保护的no-op setTotalAmount
的方法,使JPA高兴,但我不知道是否有一种方法可以让JPA知道的映射是唯一的一种方式,以避免产生多余的setter方法。
Now, I could create a protected no-op setTotalAmount
method to make JPA happy, but I was wondering if there is a way to let JPA know that the mapping is one way only and to avoid creating a superfluous setter method.
谢谢,
Aleks
Thanks, Aleks
推荐答案
你所描述的不是JPA意义上的计算属性。你在自己的方法中自己计算 - 只需将该方法标记为 @Transient
,JPA将忽略它。
What you've described is not a calculated property in JPA sense. You're calculating it yourself within your method - just mark that method as @Transient
and JPA will ignore it.
如果您确实需要计算属性(其中计算表示通过SQL表达式计算),则需要根据JPA提供程序对其进行注释。对于Hibernate,你可以通过 @Formula
注释来实现:
If you truly need a calculated property (where "calculated" means "calculated via SQL expression"), you'll need to annotate it according to your JPA provider. For Hibernate you'd do that via @Formula
annotation:
@Formula("col1 * col2")
public int getValue() {
...
}
其他提供商可能有自己的配置方式;没有JPA标准。
Other providers may have their own ways to configure this; there's no JPA standard.
这篇关于使用JPA映射计算的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!