【发布时间】:2015-07-19 07:23:36
【问题描述】:
向我的实体类添加两个OneToMany 关联似乎不起作用。如果我删除其中一个,它会正常工作。
@Entity
@Table(name = "school")
public class School {
private List<Teacher> teachers;
private List<Student> students;
@OneToMany(cascade=CascadeType.ALL, mappedBy = "school", fetch = FetchType.EAGER)
public List<Teacher> getTeachers()
return this.teachers;
}
public void setTeachers(List<Teacher> teachers) {
this.teachers = teachers;
}
@OneToMany(cascade=CascadeType.ALL, mappedBy = "school", fetch = FetchType.EAGER)
public List<Student> getStudents()
return this.students;
}
public void setStudents(List<Student> teachers) {
this.students = students;
}
}
然后在Teacher 和Student 我有正确的ManyToOne 注释
@Entity
@Table(name = "teacher")
public class Teacher {
private School school;
@ManyToOne
@JoinColumn(name = "school_id")
public School getSchool() {
return this.school;
}
public void setSchool(School school) {
this.school = school;
}
}
@Entity
@Table(name = "student")
public class Student {
private School school;
@ManyToOne
@JoinColumn(name = "school_id")
public School getSchool() {
return this.school;
}
public void setSchool(School school) {
this.school = school;
}
}
我也有带有正确注释的 id 字段(@Id、@GeneratedValue)
所以对我来说,我在同一个班级中似乎不能有多个@OneToMany。这是正确的吗?
【问题讨论】:
-
不,这根本不正确。您可以拥有任意数量的它们。你是什么意思“它不起作用”?
-
可能是两个关系同名的问题?
-
检索用户时,数据库没有返回任何内容。没有堆栈跟踪,甚至没有警告。我可以看到hibernate正在映射所有类
-
@Jens 变量在两个类中都称为
school,因此它们必须具有相同的mappedBy值,不是吗? -
那么hibernate执行的是什么sql语句?
标签: java hibernate jpa orm hibernate-mapping