I am migrating an application from Spring 3 to Spring 4. In particular, I am migrating it to
<spring.version>4.2.9.RELEASE</spring.version>
<org.springframework.ws.version>3.0.8.RELEASE</org.springframework.ws.version>
<hibernate.version>4.3.11.Final</hibernate.version>
Here is the original code that worked with Spring 3:
public AcmeUserBean loadUserByDn(String userDn) {
AcmeUserBean result = null;
Session session = null;
try {
session = this.currentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(
"from AcmeUserBean as user where user.distinguishedName = :userDn");
query.setString("userDn", userDn);
List objs = query.list();
if (objs != null && objs.size() > 0) {
result = (AcmeUserBean) objs.get(0);
}
tx.commit();
session.close();
return result;
} finally {
if (session != null) {
session.flush();
session.close();
}
}
}
With Spring 4, I updated it to:
@Transactional
public AcmeUserBean loadUserByDn(String userDn) {
AcmeUserBean result = null;
Session session = null;
try
{
session = this.getSessionFactory().getCurrentSession();
Query query = session.createQuery(
"from AcmeUserBean as user where user.distinguishedName = :userDn");
query.setString("userDn", userDn);
List objs = query.list();
if (objs != null && objs.size() > 0) {
result = (AcmeUserBean) objs.get(0);
}
return result;
} finally {
if (session != null) {
session.flush();
session.close();
}
}
}
Each line in the method succeeds and result is not null at the return line. However, an exception occurs when the method exits:
org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: commit failed
The containing class is a 'Dao' class and is annotated as @Repository.
First of all, is my migration of the code correct? Second, what is causing the exception and how can I fix it?
try/finally. Spring is managing the session and you shouldn't interfere with that. But why change the code, if it works with Spring 3, it will still work with Spring 4. I would first upgrade Spring then optimize the code, optimizing the code has nothing to do with the Spring version. .