標籤:
“一對多/多對一”是資料庫表關係中最常見的一種關係。兩張表通過外鍵進行關聯,實現表達“一對多/多對一”關係。外鍵通常位於”多方”表中。
用學生選課的例子 來說一下自己對這個注釋@mappedBy的理解。
關係:
學生Student 多方--------課程Course 多方
學生 Student多方--------老師 Teacher一方
mappedBy 指向的是放棄維護關係的一方。 學生與課程,即課程類放棄維護關係,外鍵在Student類中。學生與老師,即老師Teacher放棄維護關係,外鍵在學生Student類中。
@Entity@Table(name="t_student")public class Student { @Id @GeneratedValue private Integer id; //主鍵Id private String uname; //學生名字 private String pwd;// 密碼 private String phone;//手機號碼 private String email;//郵箱 /* * 外鍵通常放在 多方表中,放在學生表中.course放棄維護 */ @ManyToMany private Set<Course> courses = new HashSet<Course>(); @ManyToOne private Teacher teacher;
@Entity@Table(name="t_course")public class Course { @Id @GeneratedValue private Integer id; private String courseDesc;//課程描述 private String courseNo;//課程代號 //Course放棄 維護外鍵。 @ManyToMany(mappedBy="courses") private Set<Student>students= new HashSet<Student>();
@Entity@Table(name="t_teacher")public class Teacher { @Id @GeneratedValue private Integer id; private String name;//姓名 private String pwd;//密碼 private String phone;//手機 /* * 外鍵一般放在 多方表中. * mappedBy 指向的是 放棄 維護 關係的類.即,Teacher 類 放棄 維護關係 ,外鍵 放在Student類中,讓學生來維護 。 */ @OneToMany(mappedBy="teacher") private Set<Student>students = new HashSet<Student>();
資料庫表單
course類表單
學生類表單
學生 -老師關係表
談 Hibernate Annotation @mappedBy含義