Session.Connection() Deprecated on Hibernate

session.connection() deprecated on Hibernate?

You now have to use the Work API:

session.doWork(connection -> doSomething(connection)); 

Or, in Java < 8 :

session.doWork(
new Work() {
public void execute(Connection connection) throws SQLException
{
doSomething(connection);
}
}
);

Hibernate SessionFactory, setTransactionIsolationLevel on the fly

The "Transaction Isolation" property has got a "Connection" level, that's why you have to apply it once creating the connection and not at transaction level or (like general rule for all connection) on SessionFactory.

Considering what you are trying to do, you have actually two different options to set the transaction isolation.

The most used, clean and recommended one is by setting the specific hibernate property, like following one:

<property name="hibernate.connection.isolation">2</property>

On the specific case, value 2 correspond "READ COMMITTED".

Otherwise, you could try to get the connection instance from the Session, like following code:

Session session = sessionFactory.getSession();

try {
session.connection().setTransactionIsolation(2);
} catch (HibernateException | SQLException e) {
e.printStackTrace();
}

Please bear in mind that the above is quite a dirty way to do that and it's not guarantee that it works. Moreover the method connection() of org.hibernate.Session is deprecated, so you should not use it.

However, I personally used for some unit tests (as an experiment) and it worked fine.

Alternative to using deprecated save method in hibernate

save() is deprecated since Hibernate 6.0. The javadoc suggests to use persist() instead.

Deprecated.

use persist(Object)

Small print: save() and persist() are similar, but still different. save() immediately persist the entity and returns the generated ID. persist() just marks the entity for insertion. The ID, depending on the identifier generator, may be generated asynchronously, for example when the session is flushed.

How to get jdbc connection from hibernate session?

Here is how you can use it:

session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
//connection, finally!
}
});


Related Topics



Leave a reply



Submit