public void saveObject(Object object){
      
        Session session = null;
        
        try{
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
            session.save(object);
            tx.commit();
        }catch(Throwable th){
            th.printStackTrace();
        }finally{
            if(session!=null){
                try{
                    session.close();
                }catch(Throwable th){
                    th.printStackTrace();
                }
                session = null;
            }
        }
    }

解决方案 »

  1.   

    使用session管理:直接调用该类的currentSession就可以了
    session管理:
    import net.sf.hibernate.*; 
    import net.sf.hibernate.cfg.*; public class HibernateUtil {     private static Log log = LogFactory.getLog(HibernateUtil.class);     private static final SessionFactory sessionFactory;     static { 
            try { 
                // Create the SessionFactory 
                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(); 
        } 
    }