两张表 Address Person
多个人对应一个地址,ManyToOne,在人一方,增加外键,对应实体类就是增加Address address字段
在字段的get方法上增加 @ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
查询语句:
Person p =(Person)session.get(Person.class, 1); System.out.println(p.getPersonName());
执行时,sql会打印如下语句:
Hibernate: select person0_.person_id as person_i1_1_0_, person0_.address_id as address_3_1_0_, person0_.person_name as person_n2_1_0_, address1_.address_id as address_1_0_1_, address1_.address_name as address_2_0_1_ from t_person person0_, t_adress address1_ where person0_.address_id=address1_.address_id(+) and person0_.person_id=?
说明进行了级联抓取。
设置fetch=FetchType.LAZY
执行时,sql打印如下:
Hibernate: select person0_.person_id as person_i1_1_0_, person0_.address_id as address_3_1_0_, person0_.person_name as person_n2_1_0_ from t_person person0_ where person0_.person_id=?
说明没有进行级联抓取。
System.out.println(p.getAddress().getAddressName());
再执行这条语句,sql打印如下:
Hibernate: select person0_.person_id as person_i1_1_0_, person0_.address_id as address_3_1_0_, person0_.person_name as person_n2_1_0_ from t_person person0_ where person0_.person_id=? Hibernate: select address0_.address_id as address_1_0_0_, address0_.address_name as address_2_0_0_ from t_adress address0_ where address0_.address_id=?
是进行了两次查询,也就是说是需要时,再去查询的。
而设置成fetch=FetchType.EAGER
sql打印如下:
Hibernate: select person0_.person_id as person_i1_1_0_, person0_.address_id as address_3_1_0_, person0_.person_name as person_n2_1_0_, address1_.address_id as address_1_0_1_, address1_.address_name as address_2_0_1_ from t_person person0_, t_adress address1_ where person0_.address_id=address1_.address_id(+) and person0_.person_id=?
执行的是一条语句。
总结: 使用lazy,用到的时候,再去数据库中查询,提高了效率。