1

I've an entity where one field B might depend on field A (just for certain cases). To make sure that they are both updated if needed (to avoid that someone else using the entity forgets about the dependency) I tried something like this:

public void setA(A a) {
    this.a = a;

    if (condition) {
        this.b = someCalculation(a);
        // setB(someCalculation(a)); Doesn't work either!
    }
}

The code is executed and the value for B is filled correctely. However, B is not persisted.

Is somthing like this just not possible? Why isn't hibernate aware of the change of B?

Thanks in advance,

Alex

Alex
  • 160
  • 9
  • Are you sure the object is persisted after all changes? Can you show more code ? By the way this code smells, I suggest to move out this logic out of setter to some separate method/class – artjomka Mar 27 '14 at 07:55
  • Yes, because Field A is persisted correctly. – Alex Mar 27 '14 at 08:22

1 Answers1

0

You should use a setter not accessing the field directly. Take into consideration that with Hibernate/JPA entities are proxied, so certain operations are performed when they change (methods are used).

You may also have to review the relationship between main entity and "b" entity so when setting a new "b" entity is automatically persisted (cascade operations)

Community
  • 1
  • 1
Fernando Miguélez
  • 11,196
  • 6
  • 36
  • 54
  • I first used the setter setB() (see code above). It doesn't work either. Anyway B uses field access. – Alex Mar 27 '14 at 08:24
  • B is a field within the same entity. – Alex Mar 27 '14 at 09:22
  • B is type Date actually – Alex Mar 27 '14 at 09:31
  • If B is a simple type (such as Date) and you are using a setter, the only thing that occurs to me is that you are not actually working with a managed entity. Are you sure that your domain entity is a managed entity. How do you obtain it? Do you get a reference from entity mgr? You can debug your code and verify that your main entity is actually a proxy (you should see proxy fields) – Fernando Miguélez Mar 27 '14 at 11:37