public class HibernateUtil {
private static Log log=LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session=new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s=(Session)session.get();
//Open a new Session, if this Thread has none yet
if (s==null) {
s=sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s=(Session) session.get();
session.set(null);
if (s !=null)
s.close();
}}
尤其是下面这段------------------------------------------------
static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
加上了个static 是什么意思 有什么用 所谓的静态代码 在什么情况下执行啊
private static Log log=LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session=new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s=(Session)session.get();
//Open a new Session, if this Thread has none yet
if (s==null) {
s=sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s=(Session) session.get();
session.set(null);
if (s !=null)
s.close();
}}
尤其是下面这段------------------------------------------------
static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
加上了个static 是什么意思 有什么用 所谓的静态代码 在什么情况下执行啊
你可以把他看成声明一个静态变量,他要在构造函数之前调用的,他这样的代码的优势就是提高了代码的效率,仅仅在第一次实例或用这个类的时候才执行其中的内容。而sessionFactory=new Configuration().configure().buildSessionFactory();的意思是从HIBERNATE配制文件中进行对HIEBRNATE的配制,通俗点就是从你的hibernate.cfg.xml里拿数据了。
import java.util.ArrayList;/**
* Created by IntelliJ IDEA.
* User: huaxiaoxi
* Date: 2007-5-6
* Time: 13:32:11
* To change this template use File | Settings | File Templates.
*/
public class MainDo {
static{
System.out.println("某一个类里面的静态方法");
} //到底应该如何加载这段代码呢?
public MainDo(){
System.out.println("构造函数");
}
public static void main(String [] args){
mainDo=new MainDo();
}
} 那按理应该现打印出 某一类的静态方法 在打印出 构造函数啊
可事实上 前者根本没有打印 有大牛吗 出来解释一下