Hibernate Annotations - Which is better, field or property access?

后端 未结 25 1528
说谎
说谎 2020-11-22 15:02

This question is somewhat related to Hibernate Annotation Placement Question.

But I want to know which is better? Access via properties or access vi

25条回答
  •  迷失自我
    2020-11-22 15:23

    I prefer using field access for the following reasons:

    1. The property access can lead to very nasty bugs when implementing equals/hashCode and referencing fields directly (as opposed through their getters). This is because the proxy is only initialized when the getters are accessed, and a direct-field access would simply return null.

    2. The property access requires you to annotate all utility methods (e.g. addChild/removeChild) as @Transient.

    3. With field access we can hide the @Version field by not exposing a getter at all. A getter can also lead to adding a setter as well, and the version field should never be set manually (which can lead to very nasty issues). All version incrementation should be triggered through OPTIMISTIC_FORCE_INCREMENT or PESSIMISTIC_FORCE_INCREMENT explicit locking.

提交回复
热议问题