我有兩個類,如下圖所示如何在Hibernate中插入ManyToOne關係記錄?
Human.java
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Human implements Serializable {
private long id;
private String name;
....
}
Student.java
@Entity
@DynamicUpdate
public class Student extends MyFactories {
private List<Know> KnowList;
@OneToMany(fetch = FetchType.LAZY)
public List<Know> getKnowlist() {
return knowlist;
}
public void setKnowlist(List<Know> KnowList) {
return Knowlist;
}
}
Know.java
@Entity
public class Know implements Serializable {
private long id;
private Human hu;
private Student st;
....
@ManyToOne
public Person getHu() {
return hu;
}
@ManyToOne
public Client getSt() {
return st;
}
.... setters .....
}
代碼
Know kw = new Know();
kw.setSt(studentObject);
kw.setHu(humanObject);
session.save(kw);
tx.commit();
我能夠插入到專有表,但休眠不插入任何記錄student_know它所創建的表。
我發現這個answer,但它說我需要使用該方法,如果我總是想檢索所有記錄。我不(有時,我可能只需要檢索其專有的學生類就不列出來)
System.out.println(this.student.getKnowList().size());
當我嘗試訪問它運行到以下情況例外列表中。
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.myproject.Student.knowList, could not initialize proxy - no Session
你有沒有看過這個?http://stackoverflow.com/questions/13199045/hibernate-many-to-one-mapping-should-i-insert-this-way –
@ CPU100謝謝,但我有工廠和myfactories對象,但不知道如何將產品表連接到myfactories和工廠對象 –
學生擴展MyFactories?客戶端getSt()'和變量'Student st'你的示例代碼真的可以工作嗎? – Angga