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 do not have the appropriate device. Why is this?

In our case, we print the value returned from the recipient (to get it in the database), and the setter has no functional purpose. Therefore, we just have an empty method to get around the error condition.

+41
java hibernate getter-setter
Apr 20 '10 at 16:08
source share
5 answers

As already mentioned, if you annotate the getter method of a property, then Hibernate uses setter when reading values ​​from the database. Basically, Hibernate assumes that everything he writes to the database should ultimately be read from the database. This means that if you annotate a getter, then when reading an object from the database, it needs to call the setter.

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

If the field is obtained from other properties in the class, then why do you store it in the database? You can use the @Transient annotation to mark a field that it should not be stored in the database. You can even use the @Formula annotation @Formula that Hibernate @Formula field for you (it does this using the formula in the query that it sends the database).

+56
Apr 20 '10 at 17:28
source share

You must annotate your classes with @Entity(access = AccessType.FIELD) and annotate your attributes. This should solve your problem. The customization tool is the best way to support refactoring. And what a problem with having a small setter there.

+8
Apr 20 '10 at 16:19
source share

access = field if you do not want to use setters

 <id name="countryId" column="id" type="int"> <generator class="increment"> </generator> </id> <property name="name" column="name" access="field" type="string"></property> <property name="countryCode" column="country_code" access= "field" type="string"></property> 

+4
Dec 01 '14 at 21:11
source share

Hibernate uses the set method to initialize the object that you are reading from its database.

Maybe if you create access modifiers for the fields of default or protected or public objects, then Hibernate will initialize the fields directly without using setter (I read something, but I'm not sure if it works). But using a setter is a much more preferable way.

+1
Apr 20 '10 at 16:12
source share

If you are not using setters or using private attributes, Hibernate will have to extract the fields by reflection and do field.setAccessible (true). I do not think Hibernate is doing this.

I really don't know if we can tell Hibernate about this, but as far as I remember, by default the configuration uses setters ... Put log / sysout in the set and you will see that it uses the setter.

-2
Apr 20 '10 at 16:23
source share



All Articles