Hibernate newb尝试理解LAZY和EAGER获取之间的差异。
地址模型:
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String name;
@OneToOne(mappedBy = "department", fetch = FetchType.LAZY)
private Address address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Department [id=" + id + ", name=" + name + "]";
}
}
部门模特:
@Test
public void testDepartment() {
Long departmentID;
Department department;
Long addressId;
Address address;
try (Session session = SessionUtil.getSession()) {
Transaction tx = session.beginTransaction();
department = new Department();
department.setId(69L);
department.setName("company");
address = new Address();
address.setCity("city");
address.setStreet("street");
address.setDepartment(department);
session.save(department);
session.save(address);
departmentID = department.getId();
addressId = address.getId();
tx.commit();
}
try (Session session = SessionUtil.getSession()) {
department = session.load(Department.class, departmentID);
System.out.println(department.getId());
}
}
测试方法:
Hibernate: select department0_.id as id1_2_0_, department0_.name as name2_2_0_ from Department department0_ where department0_.id=?
Hibernate: select address0_.id as id1_0_1_, address0_.city as city2_0_1_, address0_.department_id as departme4_0_1_, address0_.street as street3_0_1_, department1_.id as id1_2_0_, department1_.name as name2_2_0_ from Address address0_ left outer join Department department1_ on address0_.department_id=department1_.id where address0_.department_id=?
1
当我在执行查询后从db加载部门对象时。
{{1}}
我很惊讶看到连接选择查询,因为我从未明确要求地址对象,应该懒得加载。