Java – Why autocommit is by default false in Hibernate when we have the Transaction management apis provided

hibernatejavaspringtransactions

I'm not getting a clear idea of why autocommit is by default false in Hibernate when we have the Transaction management apis provided.
I have three questions

  1. why autocommit mode is not recommended by Hibernate?

  2. What happens when we use autocommit = true and then use the Hibernate Transaction apis for transaction management ?

  3. When using spring declarative transaction management how @Transactional(readonly = true) will help the read only code (Hibernate code) we write?

Best Answer

I will answer one by one Starting with (2) as i don't know much about (1)

(2): autocommit=true means by default all queries get commited. In such case If

  • if there is a @Transactional on a method, it overrides the autocommit and encloses all queries into a single transaction, thus overriding the autocommit

  • if there is a @Transactional method that calls other @Transactional annotated methods, the outer most annotation should override the inner annotaions and create a larger transaction, thus annotations also override eachother.

(3): In DBs like Oracal/Mysql a read only transaction can be translated READ_ONLY level which provides no dirty reads, no unrepeatable reads but doesn’t allow any updates. That means the flush mode will be set as FlushMode.NEVER in the current Hibernate Session preventing the session from commiting the transaction. Even setReadOnly(true) will be called on the JDBC Connection which ensure that you cannot call session.flsuh() even to flush session manually.

since Spring doesn't do persistence itself, it cannot specify what readOnly should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.

Related Topic