I am very new to Hibernate. I get the error below if I refresh my jsp page a few times.
Quote:
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Communications link failure during rollback(). Transaction resolution unknown.
I guess I don't close session properly. Here is the HibernateUtil class and how I use it. Please help check it and let me know if I have done anything wrong. Really appreciate your help.
Code:
public class HibernateUtil { //copied from official Hibernate3 tutorial.
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this thread has none yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}
How I use itCode:
org.hibernate.Session ss = HibernateUtil.currentSession();
Transaction tx = ss.beginTransaction();
ArrayList<SpecialAccount> accounts = null;
try{
if (newRequest.updateDB()){
owner = newRequest.getOwner();
if(owner != null && owner.getCamsID()<1) owner.updateDB();
newRequest.setMachines(machines);
if(newRequest.checkAccountNameConflict()) throw new HibernateException("Account name already exists.");
accounts = newRequest.generateAccounts();
accounts.updateDB();
}
tx.commit();
HibernateUtil.currentSession().flush();
}
catch(Exception e){
if (tx != null) tx.rollback();
return;
}
finally{
HibernateUtil.closeSession();
}