@OneToMany (bidirectional)
假设现在有 university
和 student
两张表:
university
student
id name
id name university_id
一个大学可以有很多学生,而一个学生只能来自一个大学。学生依赖于大学存在,如果大学不存在,这个大学的学生也不存在。
很明显,在这个情况下,university
是 parent table,student
是 child table。并且,university
是 non-owning side,student
是 owning side。
@Entity
@Table(name = "university")
public class University {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "university", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<Student> students;
/* Getters and setters */
}
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "university_id")
private University university;
/* Getters and setters */
}
最后更新于