I've two jpa entities, say A and B. Entity A composes B and has a OneToOne mapping with cascade=MERGE, orphanRemoval=false, etc. The persistence execution is as below
- Create B as, B b = new B() and set only pre-persistence data, some date info is automatically set when object is saved.
- Create A as, A a = new A() and set all mandatory fields and also set b to a.
Everything is good. Both A, B are saved and good.
Next, fetch A using repository (A oldA = repo.findOne(key)). Transform oldA into another similar application object, say, appA (of Type A2) and do some application logic and then create a NEW object a1 of type entity A and map all the data from oldA.
Here the object a1 has exact similar data as fetched oldA, BUT the only different is, a1 composes a NEW B() object, say b1 and b1 has the same key as 'b' but is missing some mandatory dates (which were supposed to be set while saving, as a result of jpa annotations)
Here I've a couple of queries when saving new entity.
- When I save the entity a1, I'm getting an exception as b1 is missing mandatory attribute. I'm not getting how it worked first time and not now?
- Also, Does hibernate compare the keys of both a1 and oldA while saving a1 and executes an update() rather than an insert().?
If it is the update operation this time, then only I can get an exception as mandatory data missing on 'b1' as one of the mandatory attribute is supposed to be set during @PrePersist, not while @PreUpdate.
Why would hibernate does an update and NOT an insert ? I created NEW objects for A and B, second time.