?? hibernateutil.java
字號(hào):
package com.utils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Logger log = Logger.getLogger(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
//}catch(Exception e){
}catch(Throwable e){
log.error(e);
throw new ExceptionInInitializerError(e);
}
}
/**
使用ThreadLocal可以有效隔離執(zhí)行所使用的數(shù)據(jù),所以避開了Session的多線程之間的數(shù)據(jù)共享問題。
使用ThreadLocal thread_var=new ThreadLocal()語句生成的變量是一個(gè)只在當(dāng)前線程有效的
變量,也就是說不同線程所擁有的thread_var變量是不一樣的。在這個(gè)變量?jī)?nèi)可以用set(object)方
法放置保存一個(gè)對(duì)象,只要這個(gè)線程沒有結(jié)束,都可以通過thread_var變量的get方法取出原先放入的
對(duì)象。
*/
private static final ThreadLocal thread_var = new ThreadLocal();
public static Session currentSession(){
Session s = (Session)thread_var.get();
if (s==null){
s = sessionFactory.openSession();
thread_var.set(s);//very important
}
return s;
}
public static void closeSession(){
Session s = (Session)thread_var.get();
if (s!=null){
s.close();
}
thread_var.set(null);
}
public static void main(String[] args){
System.out.println(HibernateUtil.currentSession());
HibernateUtil.closeSession();
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -