0,0 → 1,109 |
package ak.hostadmiral.util; |
|
import net.sf.hibernate.*; |
import net.sf.hibernate.cfg.*; |
|
public class HibernateUtil |
{ |
private static Configuration configuration; |
private static SessionFactory sessionFactory; |
private static final ThreadLocal hibernateBean = new ThreadLocal(); |
|
public static Configuration getConfiguration() |
throws HibernateException |
{ |
if(configuration == null) |
configuration = new Configuration(); |
|
return configuration; |
} |
|
public static SessionFactory getSessionFactory() |
throws HibernateException |
{ |
if(sessionFactory == null) |
sessionFactory = getConfiguration().configure().buildSessionFactory(); |
|
return sessionFactory; |
} |
|
private static HibernateBean currentBean() |
throws HibernateException |
{ |
HibernateBean hb = (HibernateBean)hibernateBean.get(); |
|
if(hb == null) { |
hb = new HibernateBean(); |
hb.session = getSessionFactory().openSession(); |
hibernateBean.set(hb); |
} |
return hb; |
} |
|
public static Session currentSession() |
throws HibernateException |
{ |
return currentBean().session; |
} |
|
public static void closeSession() |
throws HibernateException, ModelException |
{ |
HibernateBean hb = (HibernateBean)hibernateBean.get(); |
|
if(hb == null) |
throw new ModelException("No session found for this thread"); |
|
hibernateBean.set(null); |
hb.session.close(); |
} |
|
public static void beginTransaction() |
throws HibernateException, ModelException |
{ |
HibernateBean hb = (HibernateBean)hibernateBean.get(); |
|
if(hb != null && hb.transaction != null) |
throw new ModelException("Transaction is already open"); |
|
currentBean().transaction = currentSession().beginTransaction(); |
} |
|
public static boolean isTransactionOpen() |
throws HibernateException, ModelException |
{ |
HibernateBean hb = (HibernateBean)hibernateBean.get(); |
|
return (hb != null) && (hb.transaction != null); |
} |
|
public static void commitTransaction() |
throws HibernateException, ModelException |
{ |
HibernateBean hb = (HibernateBean)hibernateBean.get(); |
|
if(hb == null || hb.transaction == null) |
throw new ModelException("No open transaction"); |
|
hb.transaction.commit(); |
hb.transaction = null; |
} |
|
public static void rollbackTransaction() |
throws HibernateException, ModelException |
{ |
HibernateBean hb = (HibernateBean)hibernateBean.get(); |
|
if(hb == null || hb.transaction == null) |
throw new ModelException("No open transaction"); |
|
hb.transaction.rollback(); |
hb.transaction = null; |
} |
|
static class HibernateBean |
{ |
public Session session; |
public Transaction transaction; |
} |
} |