Basics - Troubleshooting Hibernate / JDBC Connection Pool Issue

后端 未结 6 2072
Happy的楠姐
Happy的楠姐 2021-02-13 05:39

What is Hibernate\'s responsibility in regards to database connections it gets from an underlying connection pool. Does it test to see if a connection is closed before it uses i

6条回答
  •  囚心锁ツ
    2021-02-13 06:32

    I got the solution for the above exception. Just close the instance of session factory as well while closing the session .

    Look at the below Code:

    public class HibernateUtil {
        private static final SessionFactory sessionFactory = buildSessionFactory();
    
        private static SessionFactory buildSessionFactory() {
            try {
                // Create the SessionFactory from hibernate.cfg.xml
                return new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
            }
            catch (Throwable ex) {
                ex.printStackTrace();
                // Make sure you log the exception, as it might be swallowed
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
    
        public static SessionFactory getSessionfactory() {
            return sessionFactory;
        }
    
        public static Session getSession() {
            Session session=sessionFactory.openSession();
            session.getTransaction().begin();
            return session;
        }
        public static void closeSession(Session session) {
            if(session!=null )
            {
                if(session.getTransaction().isActive())
                {
                    session.getTransaction().commit();
                }
                    session.close();
                    getSessionfactory().close();
            }
        }
    }
    

    just call the method HibernateUtil.closeSession(). This will solve the problem.

提交回复
热议问题