Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We have some Hibernate getter methods annotated with both @Column and @Basic.

We get an exception if we don't have the corresponding setter. Why is this?

In our case we are deriving the value returned from the getter (to get stored in the DB) and the setter has no functional purpose. So we just have an empty method to get around the error condition..

like image 592
Marcus Leon Avatar asked Apr 20 '10 16:04

Marcus Leon


People also ask

Does Hibernate require getters and setters?

Although Hibernate does not require it, it is recommended to follow JavaBean conventions by defining getters and setters for you entities persistent attributes. You can still tell Hibernate to directly access the entity's fields.

Are getters and setters always needed?

Some data members should be read-only, so they may need getters but not setters. Some data members may need to be kept consistent with each other. In such a case you would not provide a setter for each one, but a single method for setting them at the same time, so that you can check the values for consistency.

Is getter a setter?

Getters and Setters play an important role in retrieving and updating the value of a variable outside the encapsulating class. A setter updates the value of a variable, while a getter reads the value of a variable.

Does JPA require setters?

With JPA, the default constructor is required, however, you are not required to use setters. You can choose a property access strategy(field or method) based on where you place the annotations.


1 Answers

As others have mentioned, if you annotate a property getter method, then Hibernate uses the setter when reading values from the database. Basically, Hibernate assumes that anything that it is writing to the database will eventually need to be read from the database. This implies that if you annotate a getter, then it needs to call a setter when reading the object from the database.

You can make the setter private (Hibernate will use reflection to access the setter). This is great way to preserve the contract of your class while still using Hibernate for relational mapping.

If the field is derived from other properties in the class, then why are you storing it in the database? 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).

like image 171
Jim Hurne Avatar answered Oct 04 '22 06:10

Jim Hurne