//注意:这里的session用完之后并不close,而只flush一下
    public void delCat(String strCatId) {
        try {
            Session s = HibernateSessionFactory.currentSession();            Object cat = s.load(Cat.class, strCatId);
            s.delete(cat);
            s.flush();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }----------
http://www.hibernate.org.cn:8000/92.html

解决方案 »

  1.   

    网上的代码被简化了,很不安全,spring 的方法Steve Ebersole: Here is a variation on the above ThreadLocalSession. The main difference is that it undersands the concept of nested calls. Note that this usage is meant specifically for use in CMT session beans.public class ThreadLocalSession
    {
        private static final ThreadLocal sessionContext = new ThreadLocal();     private Session session;
        private int level;    public static Session currentSession()
        throws HibernateException
        {
            SessionFactory factory = ...;
            ThreadLocalSession tlSession = (ThreadLocalSession)sessionContext.get();
            if (tlSession == null)
            {
                tlSession = new ThreadLocalSession();
                tlSession.session = factory.openSession();
                tlSession.level = 0;
                sessionContext.set( tlSession );
            }
            tlSession.level++;
            return tlSession.session;
        }    public static void closeSession()
        throws HibernateException
        {
            ThreadLocalSession tlSession = (ThreadLocalSession)sessionContext.get();
            if (tlSession == null)
            {
                return;
            }        tlSession.level--;
            if (tlSession.level <= 0)
            {
                if (tlSession.session != null && tlSession.session.isOpen())
                {
                    tlSession.session.close();
                }
                sessionContext.set( null );
            }
        }}