The transaction is optional in Hibernate. But why do we need to use it every time? Is there an alternative?


I found that using transaction is optional as hibernate application manages transaction in their own application code.But when i try to execute the code without Transaction,the code executes without any error but there is no data in the database. How can i commit my data without using Transaction(since it is optional)? What is the alternative of Transaction?

 Configuration c = new Configuration();
 SessionFactory sf = c.buildSessionFactory();

 Session s = sf.openSession();

 //Transaction t = s.beginTransaction();
 //some code

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 (c) Hibernate transaction demarcation doc

There are docs saying that Transaction is optional.

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate.Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional. Basic API's / architecture doc

What that actually means is that if you run your code in an environment (container / framework) which does transaction demarcation for you - you can skip using Hibernate API's for this.

Alternatives to this API's are Spring Declarative Transaction management (basically annotations, they have XML way too), Transaction demarcation in an EJB container, etc - those depend on where you run your code.

Transaction is basic work unit of a database and they are needed for working the DB's, somebody working with a DB should always specify where a transaction starts / ends.

You can read more on ACID guarantees for some context.