还记得每个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) {
- synchronized(SessionFactory.class){
- 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;
- }