techknow116
techknow116

Reputation: 33

Will Spring JPA repository save() do an update, sometimes?

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

  1. Create B as, B b = new B() and set only pre-persistence data, some date info is automatically set when object is saved.
  2. Create A as, A a = new A() and set all mandatory fields and also set b to a.
  3. 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.

  1. 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?
  2. 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.

Thanks

Upvotes: 3

Views: 4399

Answers (1)

dunni
dunni

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

Related Questions