我很难理解延迟获取,因为当我在一本书中读到它时我不工作,他们说在延迟获取中,jpa 只会在通过 geters 访问实体时加载实体,所以我创建了一个 Arquillian 项目来测试这个概念但它不起作用。这是我的两个实体
人
package com.actionbazaar.model;
@Entity
@TableGenerator(
initialValue = 5,
name = "PERSON_SEQ",
table = "PERSON_SEQ_TABLE",
pkColumnName = "SEQ_NAME",
pkColumnValue = "PERSON",
valueColumnName = "SEQ_VALUE")
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String fname;
private String lname;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", cascade = CascadeType.PERSIST)
List<Address> addresses;
//getters and setters
}
地址
@Entity
public class Address implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String city;
private String zip;
private String street;
@ManyToOne
private Person owner;
//getters and setters
}
我有一个使用这种方法的无状态会话 bean
public Person getFirstPerson() {
Person p = em.find(Person.class, 1);
em.detach(p);
//why this call does not create an exception
p.getAddresses().get(0);
return p;
}
因为我在访问地址之前分离了实体,所以地址列表应该是空的,当我分离它时,它不再由实体管理器管理,所以我不应该为这个人获取地址问题是我可以获取那个人的地址人,即使我有地址字段的惰性获取并在访问地址字段之前分离实体!!!!请一些人解释一下。
另一个测试
Person p= myStatlessSessionBean.getFirstPerson();
myOtherStalessSesionBean.moveAllPeopleToCity("NY");
if(p.getAddresses().get(0).getCity().equals("NY"))
{
system.out.prinln("person moved");
}
else {
system.out.prinln("person did not move");
} //prompts person did not move