Reputation: 984
I am currently upgrading our application and we are migrating from Hibernate 3.x and Spring/Spring Security 3.x to Hibernate 5.x and Spring/Spring Security 5.x respectively. We had some methods that executed native sql update queries (example 1), but after upgrading to 5.x the methods started throwing TransactionRequiredException: Executing an update/delete query exceptions. Well I tried adding the @Transactional annotation on the methods but it doesn't seem to help. I will share the old method and the upgraded method (example 2).
I don't understand how it is not working on the new version, did Hibernate change the way they treat native sql queries? Thanks for the responses.
Example 1
public void myTestMethod() {
String sql = "Update myTable set State = 1";
Session session = getSessionFactory().openSession();
Query query = session.createSQLQuery(sql);
query.executeUpdate();
session.close();
}
Example 2
public void myTestMethod() {
String sql = "Update myTable set State = 1";
Session session = sessionFactory.openSession();
Query query = session.createNativeQuery(sql);
query.executeUpdate();
session.close();
}
What am I doing wrong here? How can I execute this update without changing much in the methods (we have thousands of methods implemented). The sessionFactory
in the example 2 is injected with @Inject annotation.
Upvotes: 4
Views: 12218
Reputation: 4033
Try to use @Transactional
over your methods and use getCurrentSession()
instead of the openSession()
And your code has session.close()
statement which doesn't make sense any more, since the connection was already closed and managed by the spring. Try removing the session.close()
statement and try again
Upvotes: 2