Danial7777777

导航

hibernate二级缓存demo2

    @Test
    public void hello3(){
        
        Session session=sessionFactory.openSession();
        List list = session.createQuery("from User").list();
        System.out.println(list);
        session.close();
        
        /**
         * 由于学生的对象已经缓存在二级缓存中了,此时再使用iterate来获取对象的时候,首先会通过一条
         * 取id的语句,然后在获取对象时去二级缓存中,如果发现就不会再发SQL,这样也就解决了N+1问题 
         * 而且内存占用也不多
         */
        Session session2=sessionFactory.openSession();
        Iterator iterate = session2.createQuery("from User").iterate();
        while (iterate.hasNext()) {
            User user = (User) iterate.next();
            System.out.println(user);
            System.out.println(user.getId());
        }
        session2.close();        
    }
Hibernate: 
    select
        user0_.id as id1_5_,
        user0_.name as name2_5_ 
    from
        tt_user user0_
[User [id=1, name=aaa], User [id=2, name=bbb]]
Hibernate: 
    select
        user0_.id as col_0_0_ 
    from
        tt_user user0_
Hibernate: 
    select
        user0_.id as id1_5_0_,
        user0_.name as name2_5_0_ 
    from
        tt_user user0_ 
    where
        user0_.id=?
User [id=1, name=aaa]
1
Hibernate: 
    select
        user0_.id as id1_5_0_,
        user0_.name as name2_5_0_ 
    from
        tt_user user0_ 
    where
        user0_.id=?
User [id=2, name=bbb]
2

配置hibernate二级缓存之后:

Hibernate: 
    select
        user0_.id as id1_5_,
        user0_.name as name2_5_ 
    from
        tt_user user0_
[User [id=1, name=aaa], User [id=2, name=bbb]]
Hibernate: 
    select
        user0_.id as col_0_0_ 
    from
        tt_user user0_
User [id=1, name=aaa]
1
User [id=2, name=bbb]
2

 

posted on 2018-07-22 22:19  Danial7777777  阅读(97)  评论(0编辑  收藏  举报