我對Spring非常陌生,我試圖弄清楚如何使用@ElementCollection。ElementCollection和「未能懶惰地初始化一個角色集合」異常
我有以下類別:
@Embeddable
public class Phone {
private String type;
private String areaCode;
@Column(name="P_NUMBER")
private String number;
public Phone() {
}
public Phone(String type, String areaCode, String number) {
super();
this.type = type;
this.areaCode = areaCode;
this.number = number;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "EMP_ID")
private long id;
@ElementCollection//(fetch=FetchType.EAGER)
@CollectionTable(name = "PHONE", joinColumns = @JoinColumn(name = "OWNER_ID"))
private List<Phone> phones = new ArrayList<Phone>();;
public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
}
庫:
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long>{
public Employee findById(long id);
}
然後,我用它主要方法:
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
EmployeeRepository repository = context.getBean(EmployeeRepository.class);
Phone phone = new Phone("work", "613", "494-1234");
Employee emp = new Employee();
emp.getPhones().add(phone);
repository.save(emp);
emp = repository.findById(1);
for (Phone p : emp.getPhones()) {
System.out.println(p.getNumber());
}
context.close();
}
它拋出異常(當emp.getPhones( )被調用):線程「main」中的異常org.hibernate.LazyInitializationException:未能延遲初始化一個集合角色:elcol.repository.Employee.phones,無法初始化代理 - 沒有會話
如果我添加(fetch = FetchType.EAGER)到@ElementCollection註釋(在Employee類的上面的代碼中註釋) - 一切正常。
我該如何解決這個沒有FetchType.EAGER?
對不起,但我不明白。我在春天真的很新鮮。我如何將它添加到界面?我沒有實現這個接口。它由Spring自動生成 – LSO 2014-10-30 11:06:21
你沒有提到你正在使用Spring Data,所以我認爲你已經實現了。 – 2014-10-30 11:13:32
看到我編輯的答案,希望它有幫助。 – 2014-10-30 11:27:22