Hibernate fetch属性详解

主要参考 :http://4045060.blog.51cto.com/4035060/1088025

一、hibernate抓取策略单端代理的批量抓取fetch=select(默认)/join)

 

1)保持默认,同fetch="select" 

<many-to-one name="group" column="group_id" fetch="select" />

另外发送一条select语句抓取当前对象关联实体或集合.

测试代码

        Session session = null;
        try {
            session = HibernateUtils.getSession();
            /**
             * 只读操作,不使用事务也可进行.Hibernate建议任何操作都使用事务.
             */
            User u = (User) session.load(User.class,"402881e6466ae95a01466ae95c4d0004");// 加载User
            System.out.println("执行了session.load方法");
            System.out.println("[value]" + u.getName());
            System.out.println("[value]" + u.getGroup().getName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                // 关闭session
                session.close();
            }
        }

 执行效果

执行了session.load方法
Hibernate: 
    select
        user0_.id as id0_0_,
        user0_.name as name0_0_,
        user0_.password as password0_0_,
        user0_.createTime as createTime0_0_,
        user0_.updateTime as updateTime0_0_,
        user0_.group_id as group6_0_0_ 
    from
        TEST_User user0_ 
    where
        user0_.id=?
[value]james
Hibernate: 
    select
        group0_.id as id1_0_,
        group0_.name as name1_0_ 
    from
        TEST_Group group0_ 
    where
        group0_.id=?
[value]集团2

 

2)设置fetch="join"

 <many-to-one name="group" column="group_id" fetch="join" />

hibernate会通过select语句使用外连接来加载其关联实体或集合. 此时lazy会失效.  执行结果:一条join语句 

测试代码同上

 

执行效果

执行了session.load方法
Hibernate: 
    select
        user0_.id as id0_1_,
        user0_.name as name0_1_,
        user0_.password as password0_1_,
        user0_.createTime as createTime0_1_,
        user0_.updateTime as updateTime0_1_,
        user0_.group_id as group6_0_1_,
        group1_.id as id1_0_,
        group1_.name as name1_0_ 
    from
        TEST_User user0_ 
    left outer join
        TEST_Group group1_ 
            on user0_.group_id=group1_.id 
    where
        user0_.id=?
[value]james
[value]集团2

 

 二、hibernate抓取策略(集合代理的批量抓取,fetch=select(默认)/join/subselect)

 

 

Hibernate fetch属性详解,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。