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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With