y***m 发帖数: 7027 | 1 hiberate的管理在lazy模式等下弄起来挺麻烦,自己管理倒是很方便,但可能存在连接
没有释放的隐患。。。。
import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;
//@Component("hibernateSessionUtil")
public class HibernateSessionUtil implements Serializable {
//Create a thread local variable tLocalsess, for operating session
public static final ThreadLocal tLocalsess = new ThreadLocal();
//Create a thread local variable tLocaltx, used to operate services
public static final ThreadLocal tLocaltx = new ThreadLocal();
//get session
public static Session currentSession(){
//TLocalsess variables from the thread in the current session to obtain
Session session = (Session) tLocalsess.get();
//Determine whether the session is empty, if empty, will create a session
, and pay variable tLocalsess thread
try{
if (session == null){
session = openSession();
tLocalsess.set(session);
}
}catch (HibernateException e){
e.printStackTrace();
}
return session;
}
//close current session
public static void closeSession(){
//TLocalsess variables from the thread in the current session to obtain
Session session = (Session) tLocalsess.get();
//set current tLocalsess as null
tLocalsess.set(null);
try{
//close session
if (session != null && session.isOpen()){
session.close();
}
}catch (HibernateException e){
e.printStackTrace();
}
}
//start transaction
public static void beginTransaction(){
//Variables obtained from the thread of things tLocaltx Transaction
Management Object
Transaction tx = (Transaction) tLocaltx.get();
try{
//If it is empty from the session to create a tx
if (tx == null){
tx = currentSession().beginTransaction();
tLocaltx.set(tx);
}
}catch (HibernateException e){
e.printStackTrace();
}
}
//commit transaction
public static void commitTransaction(){
//get the transaction
Transaction tx = (Transaction) tLocaltx.get();
try{
//if not null, then commit
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
tx.commit();
//close current session
closeSession();
tLocaltx.set(null);
}catch (HibernateException e){
e.printStackTrace();
}
}
//rollback the transaction
public static void rollbackTransaction(){
//get tx transaction
Transaction tx = (Transaction) tLocaltx.get();
try{
//Clear the variable
tLocaltx.set(null);
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
//rollback the transaction
tx.rollback();
}
}catch (HibernateException e){
e.printStackTrace();
}
}
//private
//get session
private static Session openSession() throws HibernateException{
return getSessionFactory().openSession();
}
//get sessionFactory
private static SessionFactory getSessionFactory() throws
HibernateException{
return HibernateSessionFactory.getSessionFactory();
}
} | t*******e 发帖数: 684 | 2 google "open session in view" |
|