As we all know that in Hibernate if no transaction commit, the changes won’t affect in database. But I found something weird. And the code as follows:
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring.xml");
SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Model model = new Model();
...
session.save(model);
session.flush();
session.close();
And the model was saved to database even there’s no transaction, anyone can explain this?
Any comments would be appreciated! Thanks!
PS: I am using mysql.
Hibernate doesn’t need transactions, the most common problems in database-based applications are just easier to solve with transactions which is why usually everyone uses transactions with Hibernate. But that’s mere coincidence/convention/laziness.
All Hibernate needs is a
java.sql.Connectionand if your container provides one even though there is no current transaction manager configured, Hibernate is fine with that.In fact, Hibernate has no idea that there might be a transaction manager. So
session.flush()will use theApplicationContextto get a connection, generate the SQL and use JDBC to send the generated SQL code to the database.From Hibernate’s point of view, that’s all that happens.
There can be several reasons why the data is committed to the database:
@Transactional; in this case, you inherit the existing transaction.