2012-11-30 54 views
2

我想有一個實體屬性,休眠保存到數據庫,但不嘗試設置時,它重建對象。Hibernate實體屬性與getter,但沒有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個空白setter混淆我的代碼。

有沒有一個優雅的解決方案呢?

回答

4

Does Hibernate always need a setter when there is a getter?

在課程使用

@Entity(access = AccessType.FIELD) and annotate your attributes.

You can use the @Transient annotation to mark the field that it shouldn't be stored in the database. You can even use the @Formula annotation to have Hibernate derive the field for you (it does this by using the formula in the query it sends to the database).