I am struggling to apprehend the slight differences between the hibernate methods
saveOrUpdate - update - save/persist
.
I know there are some similar questions on the site:
What are the differences between the different saving methods in Hibernate?
Difference between save and saveOrUpdate method hibernate
but having read them, I did not notice an answer covering all the issues coming from using those methods in any case. I would to mention the example I have created to test: I have a table USER with the records:
id | company
1 Company1
2 Company2
I execute then the code:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
User user1 = (User) session.load(User.class, Integer.valueOf(1));
user1.setCompany("Company3");
User user2 = (User) session.load(User.class, Integer.valueOf(2));
user2.setCompany("Company4");
session.persist(user1);
session.save(user2);
tx.commit();
I see in the database:
id | company
1 Company3
2 Company4
I notice that save
and persist
in this case do the same task as saveOrUpdate
or update
.My question is therefore what is the diferrence between them and when are saveOrUpdate
or update
necessary. Am I right that with save
or persist
the associated objects are not updated even if using Cascade
?