1

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?

Yon
  • 1,023
  • 4
  • 13
  • 23

2 Answers2

2

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 @Transient to make Hibernate ignore it).

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • What if we're required to use property accessors? – Yon Nov 15 '11 at 10:55
  • It may be important to know that it should be avoided to mix field and property access with annotations as Hibernate will guess the access type from the position of Id or EmbeddedId. – Christoph Jul 26 '12 at 08:17
0

Hibernate won't do that. That's business logic that belongs in your code, not Hibernate. It's an ORM solution that does one thing: persist objects. It try to make you forget that there's a relational database doing the work in the back.

What you're talking about is business logic based on source and something else that you might have in mind but haven't expressed. Only you can write that. Put it in a service that implements the use case. If it's a cross-cutting concern, put it in an aspect.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • I'm not sure I understand. Should this logic NOT be implemented in the set function? – Yon Nov 15 '11 at 10:54
  • Should be implemented somewhere in your code. Hibernate will just be part of the implementation. I'd put that logic outside the persistence class. – duffymo Nov 15 '11 at 13:38