还记得每个hibernate初学者都会被指导使用这样的函数来获取数据库资源
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
当你打开TOmcat的时候,一下有几十人来访问你的页面,那么这个函数很有可能就会初始化失败了。多年前实践中总结出来,修改一下,今天想到在这里写一下:
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
[color=red]synchronized(SessionFactory.class){[/color]
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
实际上就是一个同步问题,避免多个人同时进入hibernate初始化
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
当你打开TOmcat的时候,一下有几十人来访问你的页面,那么这个函数很有可能就会初始化失败了。多年前实践中总结出来,修改一下,今天想到在这里写一下:
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
[color=red]synchronized(SessionFactory.class){[/color]
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
实际上就是一个同步问题,避免多个人同时进入hibernate初始化