Reputation: 39
I had read many websites and they says that using transaction is optional as hibernate application manages transaction in their own application code.
But when I check code it always uses transaction?
What is the correct methodology?
Configuration c = new Configuration();
c.configure("hibernate.cfg.xml");
SessionFactory sf = c.buildSessionFactory();
Session s = sf.openSession();
Transaction t = s.beginTransaction();
//some code
t.commit();
Upvotes: 2
Views: 684
Reputation: 251
Add the following tag in hibernate property file
<prop key="hibernate.current_session_context_class ">thread</prop>
or if you are using spring, then you can use @Transactional annotation to handle the transaction automatically.
Upvotes: 0
Reputation: 691685
Here's what the official documentation says:
Database, or system, transaction boundaries are always necessary. No communication with the database can occur outside of a database transaction (this seems to confuse many developers who are used to the auto-commit mode). Always use clear transaction boundaries, even for read-only operations. Depending on your isolation level and database capabilities this might not be required, but there is no downside if you always demarcate transactions explicitly. Certainly, a single database transaction is going to perform better than many small transactions, even for reading data.
Upvotes: 4