[英]Hibernate - PropertyNotFoundException: Could not find a getter for
[英]Hibernate entity attribute with getter, but without setter: PropertyNotFoundException
我想要一個實體屬性,它可以在休眠狀態下保存到數據庫中,但在重建對象時不會嘗試設置。
我有一堂這樣的課;
@Entity
class Quote {
private int itemCost;
private int quantity;
public Quote(int itemCost, int quantity) {
this.itemCost = itemCost;
this.quantity = quantity;
}
public void setItemCost(int itemCost) {
this.itemCost = itemCost;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getItemCost() {
return this.itemCost;
}
public int getQuantity() {
return this.quantity;
}
// This attribute "totalCost" has a getter only, no setter.
// It causes a runtime error (see below).
public int getTotalCost() {
return this.itemCost * this.quantity;
}
}
我想要以下數據庫表;
quotes
itemCost | quantity | totalCost
------------------------------------
100 | 7 | 700
10 | 2 | 20
6 | 3 | 18
如您所見,“totalCost”字段可以從getTotalCost()
,但我不想使用setTotalCost()
方法,在我的應用程序中它沒有任何意義。
我希望將字段寫入未再次set
的數據庫的原因是,此值可用於共享數據庫的其他應用程序(即圖形界面)。
顯然,在運行時我目前收到此錯誤:
org.hibernate.PropertyNotFoundException: Could not find a setter for property totalCost in class Quote
我可以有一個空的二傳手,但這是不干凈的。 在我的實際代碼中,大約有 13 個這樣的“只讀”屬性,我不希望 13 個空白設置器使我的代碼變得混亂。
有沒有優雅的解決方案?
請參閱當有 getter 時,Hibernate 是否總是需要一個 setter? :
在課堂上使用
@Entity(access = AccessType.FIELD) 並注釋您的屬性。
或者
您可以使用@Transient 批注來標記不應存儲在數據庫中的字段。 您甚至可以使用 @Formula 注釋讓 Hibernate 為您派生字段(它通過在發送到數據庫的查詢中使用公式來實現這一點)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.