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?
It might be because of the session is closed. In methods with Spring managed transaction (@Transactional
) ,Spring will handle session commit and session close. If you do session.close()
, the above error will appear. comment session.close()
and try it.
@Transactional
public AcmeUserBean loadUserByDn(String userDn) {
AcmeUserBean result = null;
Session 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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments