【发布时间】:2022-01-11 10:53:09
【问题描述】:
我有两张表,student 和 teacher,关系为 ManyToOne。表结构如下
student(
id long,
student_id string,
....
teacher_id string,
active boolean
)
teacher(
id long,
teacher_id string,
....
active boolean
)
我正在使用 Spring Boot 和 Hibernate。此处更新实体时,表中现有行的活动列将设置为 false,并且将添加一个新行,并使用新的 id(long) 和活动为 true。这就是为什么每个表中有两个 id 值。这里的问题是我已经在我的实体中指定了学生与教师的关系,外键为teacher_id。
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "student_id")
private String studentId;
@ManyToOne
@JoinColumn(name = "teacher_id", referencedColumnName = "teacher_id")
private Teacher teacher;
@Column(name = "active")
@JsonIgnore
private Boolean active = true;
}
@Entity
@Table(name = "teacher")
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "teacher_id")
private String teacherId;
@OneToMany(mappedBy = "teacher")
private Set<Student> students = new HashSet<>();
@Column(name = "active")
@JsonIgnore
private Boolean active = true;
}
但是由于可以使用相同的teacher_id 出现多个教师,因此失败了。有没有办法给关系提供条件以获取 active 为 true 的老师?在表中,将只有一位具有给定 id 且 active 为 true 的教师。
【问题讨论】:
-
您可能还应该包含
Teacher的实体类。 -
添加了教师实体@TimBiegeleisen
-
“多个教师可以使用相同的teacher_id”->这应该是不可能的。它违背了 id 的全部目的。
-
Teacher实体的主键是id,不是teacher_id。当实体更新时,id 会改变。并且学生实体映射到teacher_id而不是id。
-
@Nipun 这没有任何意义,因为那个“id”有/可以是重复的,你永远不会知道你的学生实际映射到哪个老师
标签: java spring-boot hibernate many-to-one