HibmentはopsessionをテストしてgetCurrentSessionの原理を実現します

1894 ワード

public class HibmentUtil {
    //  ThreadLocal
    static  ThreadLocal telSession;
    static Configuration cfg;
    static SessionFactory factory;
    static {
        //  Confing  
        cfg=new Configuration().configure();

         factory = cfg.buildSessionFactory();

        telSession=new ThreadLocal();
    }
    //     
    public  static  Session getSession(){
        //       
        Session session = telSession.get();
        if(session==null){
             session = factory.openSession();
            //  Session
            telSession.set(session);
        }
        return session;
    }
    //     
    public  void closeSession(){
        Session session = telSession.get();
        if (session!=null){
            session.close();
            telSession.set(null);
        }
    }
}
 
public class text20171006 {

    Configuration cfg;
    Session session;
    Transaction tx;
    SessionFactory factory;

    @Before
    public  void before(){
        cfg=new Configuration().configure();
        factory = cfg.buildSessionFactory();
        session = HibmentUtil.getSession();
        Session session1=HibmentUtil.getSession();

        System.out.println(" :"+session);
        System.out.println(" :"+session1);
        tx = session.beginTransaction();
    }
    @Test
    //    
    public  void  aVoid(){
        //String hql="from Dept";
        String hql="from Emp";
        Query query = session.createQuery(hql);
        int pageIndex=2;
        int pageSize=3;
        query.setFirstResult((pageIndex-1)*pageSize);
        query.setMaxResults(pageSize);
        List list = query.list();
        for (Emp item:list
             ) {
            System.out.println(item.getEname());
        }
    }


}