我有3个名为A,B,C的类,如下所示:
A类:
@Entity
public class A implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne(cascade = CascadeType.PERSIST)
private B b;
//Getters and Setters
}
B组:
@Entity
public class B {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne(cascade = CascadeType.PERSIST)
private C c;
//Getters and Setters
}
C类:
@Entity
public class C implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
//Getters and Settters
}
当我使用方法时:
em.find(A.class, a.getId());
hibernate生成以下sql查询:
Hibernate :
select
a0_.id as id1_0_0_,
a0_.b_id as b_id2_0_0_,
b1_.id as id1_1_1_,
b1_.c_id as c_id2_1_1_,
c2_.id as id1_2_2_
from
A a0_
left outer join
B b1_
on a0_.b_id=b1_.id
left outer join
C c2_
on b1_.c_id=c2_.id
where
a0_.id=?
并加载所有三个对象,但我不希望hibernate走得那么远。 我试图通过设置
为休眠设置最大获取部门<property name="hibernate.max_fetch_depth" value="0"/>
所以hibernate只针对A类的一个对象,但生成的sql查询变成了这个:
Hibernate:
select
a0_.id as id1_0_0_,
a0_.b_id as b_id2_0_0_
from
A a0_
where
a0_.id=?
Hibernate:
select
b0_.id as id1_1_0_,
b0_.c_id as b_id2_1_0_
from
B b0_
where
b0_.id=?
Hibernate:
select
c0_.id as id1_2_0_,
from
C c0_
where
c0_.id=?
因为它很清楚,hibernate再次获取了所有三个对象。
正如documentation所说:
max_fetch_depth: 设置最大&#34;深度&#34;用于单端关联的外连接获取树(一对一,多对一)。 A 0禁用默认外部联接提取。
它只影响外连接而不是一般的最大提取深度。
有什么办法在尝试获取A的对象时,hibernate只会带来1级关联? (我的意思是A的对象有b但是b没有c)