0

I have the below code which tries to save the entity outside the transaction:

Session session = HibernateUtil.buildSessionFactory().openSession();
Teacher t= new Teacher();
t.setName("jonathan");
session.save(t);
session.flush();

According to the definition of save() if used outside the transaction we need to do flush() to save the entity in the db.However the above code does not save it. I have to create a transaction and commit it in order to add a row in db. Why is this so?

I am using HIbernate 4.3.6

EDIT: I just noticed that the session.save() returns the id but only after transaction.commit() the row is added.The other question does not answer my question.Since this basically means that save() in order to add the row in db has to be in a transaction only

ghostrider
  • 2,046
  • 3
  • 23
  • 46
  • Possible duplicate of [hibernate save method - outside of transaction](https://stackoverflow.com/questions/41413063/hibernate-save-method-outside-of-transaction) – Rann Lifshitz Apr 22 '19 at 13:10
  • The added question does not answer my question.My code essentially says that the save to work correctly, it has to be inside a transaction – ghostrider Apr 22 '19 at 13:26
  • I don't think you can get around the explicit call to the `commit` since this is the Hibernate way of transferring the data from your session to the DB. See: http://www.tecbar.net/difference-flush-commit-hibernate/ – Rann Lifshitz Apr 22 '19 at 13:48
  • Then what's the use of using save() outside transaction since it does not save the entity in the db. – ghostrider Apr 22 '19 at 13:50
  • Based on the following : https://github.com/awantik/MindTree-Hibernate-7/wiki/6.-Important-Hibernate-Functions---save,-persist,-saveOrUpdate,-update,-merge,-get,-load - the issue might be with the save occurring BEFORE the flush. – Rann Lifshitz Apr 22 '19 at 14:13
  • The git link says primary object gets saved and secondary doesn't before flush.Mine is primary so should get saved.. – ghostrider Apr 22 '19 at 15:13
  • Did you try to first flush, then save? – Rann Lifshitz Apr 22 '19 at 15:28
  • Yes, it didnt work – ghostrider Apr 22 '19 at 17:02
  • Work with a transaction then. Any reason not to? – Rann Lifshitz Apr 23 '19 at 07:18
  • I am just trying to understand the purpose of using save then. – ghostrider Apr 23 '19 at 07:59
  • https://www.journaldev.com/3481/hibernate-session-merge-vs-update-save-saveorupdate-persist-example Sounds like there might be some bug on your end. Depends on your entity module, I suspect..... – Rann Lifshitz Apr 23 '19 at 08:31
  • Please look at the link I mentioned in the answer – ghostrider Apr 23 '19 at 10:48
  • As quoted from @ghostrider: After a lot of searching found out this https://stackoverflow.com/a/47414189/1337007 which states that only flush() does not commit the changes you need to explicitly commit those changes – Rann Lifshitz Apr 23 '19 at 13:37

0 Answers0