首页 > 代码库 > Hibernate fetch属性详解
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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。