Hi,
I am a beginner in hibernate. I am facing a problem when I am trying to create nested transactions.
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: lib.LibStudent.transactions, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:119)
at org.hibernate.collection.PersistentSet.isEmpty(PersistentSet.java:169)
Code:
public String onSubmit() {
Session sessionUtil = HibernateUtil.getSessionFactory().openSession();
sessionUtil.setFlushMode(FlushMode.MANUAL);
sessionUtil.beginTransaction();
try {
// nested transaction call
LibLogin result = LibLoginDAO.getUser(loginObj.getUserID());
if (null != result) {
Set<LibTransaction> tranSet = result.getLibStudent()
.getTransactions();
// this piece of code is giving error
if (null != tranSet && !tranSet.isEmpty()) {
session.put("issuedBookList", tranSet);
}
return "student";
}
} else {
return "failure";
}
}
} catch (HibernateException e) {
e.printStackTrace();
sessionUtil.getTransaction().rollback();
} finally {
sessionUtil.getTransaction().commit();
sessionUtil.flush();
sessionUtil.close();
}
return "failure";
}
Nested Transaction method:
public static LibLogin getUser(String userId) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
LibLogin login = null;
List<LibLogin> loginList= session.createQuery("from lib.LibLogin where userid ='" + userId +"'").list();
if(loginList.size()==1){
login=(LibLogin)loginList.get(0);
}
session.getTransaction().commit();
return login;
}
IF I do the following changes in getUser() method :
Session session = HibernateUtil.getSessionFactory().openSession();
and block the
//session.close();
no exception in this case, but I want make the whole transaction Atomic.
kindly advice what is wrong with the code.