Question

In the application that i'm working on, i have a senario,

UI updates some data which is already retrived from the database and sends an object back to the server(say using EntityTag.java), Server retrives the object again from the DB(say Entity.java which is mapping file in hibernate) and copies all the values from the EntityTag into Entity.java objct.

Now, using some service, it tries to save the updated Entity.java object. This is does in spring declarative transactions. So, i'm assuming that the new transaction is started on this service.

What I was hoping to see in this service method is a session. merge() because, we updated an object which was detached, but here they use saveOrUpdate on the entity.java object. I see that the object is updated into the table without any issues. This is so wierd, until now i've been thinking that the merge will merge the object into the session and later, i can commit the changes, this seems soo wierd to me.

In what cases does saveandupdate work without issues?

enter image description here

Était-ce utile?

La solution

See this answer, saveOrUpdate works well if there is never the risk that there is not already an object with the same database identifier associated to the session where saveOrUpdate is being called.

If an object already exists with the same database Id, saveOrUpdate throws an error, while merge will just replace the object in the session with the new object and return a reference to the new attached object.

Hibernate had a method called saveOrUpdateCopy that provided the same as current merge, which got standardized as merge in JPA.

Although saveOrUpdateis still available and used in many tutorials, you would be better off always using merge when dealing with detached objects, as it's hard / error prone to try to guess if an object is already in a session.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top