How is transaction isolation level management implemented in Hibernate?
sobes.tech AI
Answer from AI
Management of transaction isolation levels in Hibernate is carried out in the following ways:
-
Via configuration files
hibernate.cfg.xmlorpersistence.xml: The isolation level is set globally for the entireSessionFactoryusing the propertyhibernate.connection.isolation:<property name="hibernate.connection.isolation">4</property> <!-- For example, READ_COMMITTED -->The value is specified as a numeric code corresponding to JDBC isolation levels (
Connection.TRANSACTION_READ_UNCOMMITTED = 1,TRANSACTION_READ_COMMITTED = 2,TRANSACTION_REPEATABLE_READ = 4,TRANSACTION_SERIALIZABLE = 8). -
Programmatically, when obtaining a connection: The isolation level can be set directly on the JDBC
Connectionobtained fromSessionFactory:// Obtaining connection from SessionFactory Connection connection = sessionFactory.getSessionFactoryOptions().getServiceRegistry().getService(org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess.class).obtainConnection(); // Setting the isolation level connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // ... working with the connection ... connection.close();This method is used less frequently and may be useful for specific tasks.
-
Via Spring transaction API (when using Spring Framework): In Spring transaction configuration, you can specify the
isolationattribute. Spring's TransactionManager will manage the isolation level based on this setting.@Transactional(isolation = Isolation.READ_COMMITTED) public void myTransactionalMethod() { // ... transaction code }Spring prefers setting the isolation level on the JDBC
Connectionobtained from the connection pool managed by Spring. Hibernate will use this isolation level for the session tied to the current Spring transaction.
Important points:
- Setting the isolation level via
hibernate.connection.isolationapplies by default to all transactions created by thisSessionFactory. - Setting the isolation level programmatically or through Spring overrides the global setting for a specific transaction or method.
- Available isolation levels depend on the database and JDBC driver used. Some levels may not be supported or may behave differently across databases.
- Changing the isolation level during an active transaction is usually not possible and may lead to errors. The isolation level should be set before starting the transaction.