Let’s say I define a set of get and set functions for a given property in a class that gets handled by Hibernate. The set function is a public one which may be called by Hibernate’s mechanisms as well as normal flow of code.
If the set function is called by Hibernate, it should just set the field’s value. If the set is called by another source, it should also update additional fields accordingly.
Is there a way in code to differentiate between the two situations? Or, is there a better practice for handling this situation?
The easiest way to handle it is to configure Hibernate to access fields directly rather than through the methods. In that case you can implement any kind of logic in your getters and setters, and Hibernate won’t trigger it.
If you use annotation-based approach, this behaviour can be configured by placing annotation on fields.
If you have to use property accessors, you can create two properties backed by the same field – one for Hibernate (it can be non-
public), and another one for other code (it should be annotated as@Transientto make Hibernate ignore it).