为什么在控制台会提示这样的信息: WARN [ConnectionManager] unclosed connection, forgot to call close() on your session? ---------------------------------------------------------------- 我是用spring+hibernate架构的,在数据库访问类DAO中extends HibernateDaoSupport。 我是用myeclipse做的,它帮我自动生成了SessionFactory类:
import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration;
/
*/
public class HibernateSessionFactory {
/
- Location of hibernate.cfg.xml file.
- NOTICE: Location should be on the classpath as Hibernate uses
- #resourceAsStream style lookup for its configuration file. That
- is place the config file in a Java package - the default location
- is the default Java package.
- Examples:
CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
- CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".
/ Holds a single instance of Session */ private static final ThreadLocal threadLocal = new ThreadLocal();
/ The single instance of hibernate configuration */ private static final Configuration cfg = new Configuration();
/ The single instance of hibernate SessionFactory */ private static org.hibernate.SessionFactory sessionFactory;
/
- Returns the ThreadLocal Session instance. Lazy initialize
- the
SessionFactory
if needed.
- @return Session
- @throws HibernateException
if (session == null || !session.isOpen()) { 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 != null) ? sessionFactory.openSession() : null; threadLocal.set(session); }
return session; }
/
*
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) { session.close(); } }
/
- Default constructor.
} -------------------------------------------------------- DAO基本都是这样的: public class TAreaDAO extends HibernateDaoSupport {
public TAreaDAO(){ super(); } ..... .....
public static TAreaDAO getFromApplicationContext (ApplicationContext ctx) { return (TAreaDAO) ctx.getBean("TAreaDAO"); } }