81,092
社区成员
发帖
与我相关
我的任务
分享
public class HibernateUtils {
private static final SessionFactory sessionfactory;
static {
try {
sessionfactory = new Configuration().configure()
.buildSessionFactory();
System.out.println("Initial SessionFactory creation ok.");
System.out.println(sessionfactory);
} catch (Throwable ex) {
ex.printStackTrace();
System.out.println("Initial SessionFactory creation failed.");
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal tLocalsess = new ThreadLocal();
public static final ThreadLocal tLocaltx = new ThreadLocal();
// 取得session
public static Session getSession() {
Session session = (Session) tLocalsess.get();
// 打开一个新的session,如果当前的不可用
try {
if (session == null || !session.isOpen()) {
session = openSession();
tLocalsess.set(session);
}
} catch (HibernateException e) {
e.printStackTrace();
}
return session;
}
public static void closeSession() {
Session session = (Session) tLocalsess.get();
tLocalsess.set(null);
try {
if (session != null && session.isOpen()) {
session.close();
}
} catch (HibernateException e) {
e.printStackTrace();
}
}
public static void beginTransaction() {
Transaction tx = (Transaction) tLocaltx.get();
try {
if (tx == null) {
tx = getSession().beginTransaction();
tLocaltx.set(tx);
}
} catch (HibernateException e) {
e.printStackTrace();
}
}
public static void commitTransaction() {
Transaction tx = (Transaction) tLocaltx.get();
try {
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
tx.commit();
}
} catch (HibernateException e) {
e.printStackTrace();
}
}
public static void rollbackTransaction() {
Transaction tx = (Transaction) tLocaltx.get();
try {
tLocaltx.set(null);
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
tx.rollback();
}
} catch (HibernateException e) {
e.printStackTrace();
}
}
private static Session openSession() throws HibernateException {
return getSessionFactory().openSession();
}
private static SessionFactory getSessionFactory() throws HibernateException {
return sessionfactory;
}
}
package com.bjsxt.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory factory;
static {
try {
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return factory;
}
public static Session getSession() {
return factory.openSession();
}
public static void closeSession(Session session) {
if (session != null) {
if (session.isOpen()) {
session.close();
}
}
}
}