每个人都对使用注释@OneToMany
/ @ManyToOne
有疑问;是否可以在该模型中创建两套主题的用户模型(针对教师和参加学生的行为),而不用创建单独的学生模型和教师模型?我编写了这样的代码,但是当我想获取有关项目和用户的数据时,休眠会导致“堆栈溢出”错误崩溃。我将添加使用H2数据库的信息。
用户实体:
@Entity
public class User{
@OneToMany(
mappedBy = "student",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
orphanRemoval = true
)
private Set<Item> items = new HashSet<>();
@OneToMany(mappedBy = "teacher",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
orphanRemoval = true
)
private Set<Item> carriedItems= new HashSet<>();
}
//id and other data
项目实体:
@Entity
public class Item{
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "student_id", nullable = false)
private User student;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "teacher_id", nullable = false)
private User teacher;
}
//id and other data
感谢@Leviand
答案 0 :(得分:0)
根据您的评论,您的代码和逻辑看起来需要一些返工。
首先,使用两个专用的类代替Item
pojo:
@Entity
@Table(name = Studend) // I'm guessing a table name
public class Student{
@JoinColumn(name = "student_id", nullable = false)
private User user;
}
@Entity
@Table(name = Teacher) // I'm guessing a table name
public class Teacher{
@JoinColumn(name = "teacher_id", nullable = false)
private User user;
}
然后,由于User
仅可连接到单个Teacher
或Student
,因此请以类似的方式加以说明:
@Entity
@Table(name = User) // I'm guessing a table name
public class User{
@OneToOne(
mappedBy = "student",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
orphanRemoval = true
)
private Student student;
@OneToMany(mappedBy = "teacher",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
orphanRemoval = true
)
private Teacher teacher;
}
希望这会有所帮助:)