We are using Toplink implementation of JPA + Spring + EJB. In one of our EJBs we have something like this:
public void updateUser(long userId, String newName){
User u = em.get(User.class, userId);
u.setName(newName);
// no persist is invoked here
}
So, basically this updateUser()
method is supposed to update the name of a user with the given userId
.
But the author of this method forgot to invoke em.persist(u)
.
And the strangest thing is that it works fine. How can it be? I was 100% sure that
without invoking em.persist()
or em.merge()
there is no way that changes could have been saved into database. Could they? Is there any scenario when this could happen?
You can choose between JPA's persist and merge and Hibernate's save and update methods. It seems like there are 2 pairs of 2 methods that do the same. You can use the methods persist and save to store a new entity and the methods merge and update to store the changes of a detached entity in the database.
Kind of mysterious – all you want to do would be to update the some component on your java logic and it is automatically saved in the database.
Difference between save and persist method in Hibernate First difference between save and persist is there return type. Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.
You're working with a managed entity. If the entity does not become detached because its entity manager is closed, all changes done to the entity are reflected to the database when the session is flushed/closed and the transaction commited.
From the Java EE tutorial:
The state of persistent entities is synchronized to the database when the transaction with which the entity is associated commits.
Edit for clarity and explanation: So there are three distinct modes that an entity could be in during its lifecycle:
persist()
has not been called yet.persist()
, or loaded from the database, and is associated with an entity manager session. All changes to the entity are reflected to the database when the entity manager session is flushed.merge()
command.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With