Reputation: 1461
I would like to have a entity attribute that hibernate saves to a database, but does not try to set when it reconstructs the object.
I have a class like this;
@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;
}
}
I would like the following database table;
quotes
itemCost | quantity | totalCost
------------------------------------
100 | 7 | 700
10 | 2 | 20
6 | 3 | 18
As you can see, the field "totalCost" can be taken from getTotalCost()
, but I do not want to have a setTotalCost()
method, in my application it would make no sense.
The reason that I would like a field written to a database that is not set
again, is so this value is available to other applications that share the database (namely, the graphical interface).
Obviously, at runtime I currently get this error:
org.hibernate.PropertyNotFoundException: Could not find a setter for property totalCost in class Quote
I could have an empty setter, but this is unclean. In my real code there are about 13 "read only" attributes like this, I don't want 13 blank setters cluttering up my code.
Is there an elegant solution to this?
Upvotes: 4
Views: 5902
Reputation: 1976
See Does Hibernate always need a setter when there is a getter?:
On the class use
@Entity(access = AccessType.FIELD) and annotate your attributes.
or
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).
Upvotes: 4