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

后端 未结 25 1611
说谎
说谎 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:32

    That really depends on a specific case -- both options are available for a reason. IMO it boils down to three cases:

    1. setter has some logic that should not be executed at the time of loading an instance from a database; for example, some value validation happens in the setter, however the data coming from db should be valid (otherwise it would not get there (: ); in this case field access is most appropriate;
    2. setter has some logic that should always be invoked, even during loading of an instance from db; for example, the property being initialised is used in computation of some calculated field (e.g. property -- a monetary amount, calculated property -- a total of several monetary properties of the same instance); in this case property access is required.
    3. None of the above cases -- then both options are applicable, just stay consistent (e.i. if field access is the choice in this situation then use it all the time in similar situation).

提交回复
热议问题