07-hibernate注解-一对多(多对一)双向外键关联
一对多(多对一)双向外键
多方:多方持有一方的引用。
@ManyToOne(cascade={CasCadeType.ALL},fetch=FetchType.EAGER)
@JoinColumn(name="cid")
一方:一方持有多方的集合。
@OneToMany(@cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name="cid")
第一步:建立学生表:
1,对应学生类:因为多方持有一方,添加注解:@ManyToOne。
package otm_bfk; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity;/*JPA主键*/ import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.CacheModeType; /*学生实体类*/ @Entity @Table(name="Students",schema="sys") public class Students { private int sid; private String name; private String gender;//性别 private Date birthday; private String major;//专业 private ClassRoom classRoom;//多方持有一方的引用 public Students() { } public Students( String name,String gender, Date birthday, String major) { //super(); this.name=name; this.gender = gender; this.birthday = birthday; this.major = major; } @Id @GeneratedValue //主键自动增长 public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(name="cid") public ClassRoom getClassRoom() { return classRoom; } public void setClassRoom(ClassRoom classRoom) { this.classRoom = classRoom; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
第二部:班级类和测试类代码跟前面的一对多单向一样。
测试结果: