public class HibernateSession {
private static final ThreadLocal sessionThread = new ThreadLocal();
private static final ThreadLocal transactionThread = new ThreadLocal();
private static SessionFactory sf = null;
public static void setSessionFactory(SessionFactory _sf) {
sf = _sf;
}
public static boolean isSessionCreated() {
return (sessionThread.get() != null);
}
public static boolean isTransactionCreated() {
return (transactionThread.get() != null);
}
/**
* Current Session
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session s = (Session) sessionThread.get();
if (s == null) {
if (sf == null)
sf = new Configuration().configure().buildSessionFactory();
s = sf.openSession();
sessionThread.set(s);
}
return s;
// return sf.getCurrentSession();
}
/**
* Get a new Session
*
* @return Session
* @throws HibernateException
*/
public static Session newSession() throws HibernateException {
if (sf == null)
sf = new Configuration().configure().buildSessionFactory();
return sf.openSession();
}
/**
* Start or Add current Session's Transaction
*
* @return Transaction
* @throws HibernateException
*/
public static Transaction currentTransaction() throws HibernateException {
Transaction tx = (Transaction) transactionThread.get();
if (tx == null) {
tx = currentSession().beginTransaction();
transactionThread.set(tx);
}
return tx;
}
/**
* Commit
*
* @throws HibernateException
*/
public static void commitTransaction() throws HibernateException {
Transaction tx = (Transaction) transactionThread.get();
transactionThread.set(null);
if (tx != null)
tx.commit();
}
/**
* Rollback
*
* @throws HibernateException
*/
public static void rollbackTransaction() throws HibernateException {
Transaction tx = (Transaction) transactionThread.get();
transactionThread.set(null);
if (tx != null)
tx.rollback();
}
/**
* Close Session
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session s = (Session) sessionThread.get();
sessionThread.set(null);
if (s != null && s.isOpen()) {
try {
s.close();
}
catch (Exception e) {
}
}
// if (sf != null) {
// sf.getCurrentSession().close();
// }
}
public static void main(String[] args) {
try {
String conf = "hibernateTest.cfg.xml";
if (args.length != 0)
conf = args[0];
Configuration cfg = new Configuration().configure("/" + conf);
SchemaExport se = new SchemaExport(cfg);
se.setOutputFile("create_table.sql");
se.create(true, true);
}
catch (HibernateException e) {
System.out.println(e.getMessage());
}
}
}
HibernateSession
最新推荐文章于 2022-03-22 09:40:55 发布
