Reputation: 33
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
B b = new B()
and set only pre-persistence data, some date info is automatically set when object is saved.A a = new A()
and set all mandatory fields and also set b to a.respotory.save(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.
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.
Thanks
Upvotes: 3
Views: 4399
Reputation: 44535
Hibernate will check, if the id field is null. If so, then it will insert the data, if the id field has a value, Hibernate will do an update to the row with that id. So if you create a new object and copy values from another object, and you want to create a new entry in the database, make sure the id field stays null.
Upvotes: 2