2015-03-31 118 views
0

對不起,我的英語。我學習JavaEE,我不知道我是否在休眠時使用會話。如何使用它們?我使用模式DAOhibernate。告訴我的財產使用會話正確使用會話(休眠)

這是的HibernateUtil

private static final SessionFactory sessionFactory; 

    static { 
     try{ 
      sessionFactory = new Configuration().configure("/app/web/landingpage/HibernateConnect/hibernate.cfg.xml").buildSessionFactory(); 
     }catch(Throwable ex) { 
      System.out.println("Error " + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 
    } 

    public static SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public static void close(Session session) { 
      if (session != null) { 
       try { 
        session.close(); 
       } catch (HibernateException ignored) { 
        System.out.print("Couldn't close Session" + ignored); 
       } 
      } 
     } 

而該類如何使所有的操作分貝CategoryDaoImpl

public class CategoryDaoImpl implements CategoryDao{ 
    private Session session = null; 
    //get all category 
    public Collection getAllCategory() { 
      List categoris = new ArrayList<Category>(); 
      try{ 
       session = HibernateUtil.getSessionFactory().openSession(); 
       categoris = session.createCriteria(Category.class).list(); 
      }catch(Exception e) { 
       System.out.println("getAllCategory "+ e); 
      }finally{ 
       if(session != null && session.isOpen()) 
        session.close(); 
      } 


     return categoris; 
      } 
    //get category id 
    public Category getCategory(int id) { 

      Category cat = null; 
      try { 
       session = HibernateUtil.getSessionFactory().openSession(); 
       cat = (Category) session.load(Category.class, id); 
      }catch(Exception e) { 
       System.out.println("getAllCategory "+ e); 
      }finally{ 
       if(session != null && session.isOpen()) 
        session.close(); 
      } 
      return cat; 
     } 

//and below few methods that use it the some way session 
     } 

和這個servlet採取導致indexuser

Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 
     session.beginTransaction(); 

try{ 
      Collection allcategory = Factory.getInstance().getCatDAO().getAllCategory(); 
request.setAttribute("allcategory", allcategory); 
request.getRequestDispatcher("/index.jsp").forward(request, response); 
     } catch(Exception e) { 
      System.out.println(e); 
     } finally{ 
      if(session!=null && session.isOpen()) 
       session.close(); 
     } 

回答

3

這裏的主要合同是創建Session實例。通常應用程序具有一個SessionFactory實例,並且服務於客戶端請求的線程從該工廠獲取Session實例。

SessionFactory的內部狀態是不可變的。一旦它被創建,這個內部狀態就被設置了。這個內部狀態包括關於對象/關係映射的所有元數據。

基本會話用於獲取與數據庫的物理連接。因此,在執行任何數據庫操作時,首先會使用sessionFactory打開Session,然後使用Session與數據庫建立物理連接,然後執行您的操作,並在執行操作後關閉它。

會議重量輕。