gpt4 book ai didi

java - 如何在hibernate中插入ManyToOne关系记录?

转载 作者:行者123 更新时间:2023-11-29 05:40:05 24 4
gpt4 key购买 nike

我有如下两个类,

人类.java

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Human implements Serializable {

private long id;
private String name;
....
}

学生.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();

我能够插入到 Know 表中,但 hibernate 不会将任何记录插入到它创建的 student_know 表中。

我找到了这个 answer但它说如果我总是想检索所有记录,我需要使用该方法。我不知道(有时,我可能只需要检索学生类(class)而不是其已知的列表)

    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

最佳答案

对于选择案例,将 @OneToMany(fetch = FetchType.LAZY) 更改为 @OneToMany(fetch = FetchType.EAGER) 以便您可以在其列表中获取数据。

对于插页,我需要您说明您的关系或 private Factory fac; 的 getter setter 在哪里?

你至少应该有这样的东西:

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "YOUR_FACTORY_ID_COLUMN")
private Factory fac;

public Factory getFac(){
return fac;
}

public void setFac(Factory fac){
this.fac=fac;
}

工厂有id吗?

关于java - 如何在hibernate中插入ManyToOne关系记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17937024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com