尽管应用了延迟加载,但它仍在运行所有4个查询, 但我只提取:
System.out.println("Author's Name: " + b.getEmail());
public class Author {
@Id
@Column(name = "AUTHOR_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String email;
@OneToOne(mappedBy = "author", fetch = FetchType.LAZY)
private Book book;
@OneToOne(mappedBy = "author", fetch = FetchType.LAZY)
private Address address;
@OneToOne(mappedBy = "author", fetch = FetchType.LAZY)
private Location location;
}
public class BooksManager {
public static void main(String[] args) {
Author b = (Author) session.get(Author.class, 6L);
System.out.println("Author's Name: " + b.getEmail());
}
}
它正在对上述代码运行所有4个查询:
Hibernate: select author0_.AUTHOR_ID as AUTHOR_I1_1_0_, author0_.email as email2_1_0_, author0_.name as name3_1_0_ from AUTHOR author0_ where author0_.AUTHOR_ID=?
Hibernate: select address0_.address_id as address_1_0_0_, address0_.description as descript2_0_0_, address0_.PUBLISHED as PUBLISHE3_0_0_, address0_.title as title4_0_0_ from ADDRESS address0_ where address0_.address_id=?
Hibernate: select book0_.book_id as book_id1_2_0_, book0_.description as descript2_2_0_, book0_.PUBLISHED as PUBLISHE3_2_0_, book0_.title as title4_2_0_ from BOOK book0_ where book0_.book_id=?
Hibernate: select location0_.location_id as location1_3_0_, location0_.description as descript2_3_0_, location0_.PUBLISHED as PUBLISHE3_3_0_, location0_.title as title4_3_0_ from LOCATION location0_ where location0_.location_id=?
答案 0 :(得分:0)
在您的定义中,所有3个OneToOne关系都是可选的(可为空)。 休眠加载实体Author时,它必须创建3个代理关系。但是如果属性为null,则hibernate不应为该属性创建代理。 现在,休眠必须以某种方式知道该属性是否为null。 因此它必须查找所有其他3个表以检测到该情况。 最终,hibernate具有足够的智能,可以忽略LAZY加载的提示,并热切地加载它们。