現在有三個類:One Many Much
One類
Much類
@Entity
public class Much {
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToMany
@JoinTable(
name = "much_more",
joinColumns= {@JoinColumn(name = "many_id", referencedColumnName = "id")},
inverseJoinColumns= {@JoinColumn(name = "much_id", referencedColumnName = "id")})
private List<Many> manys;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Many> getManys() {
return manys;
}
public void setManys(List<Many> manys) {
this.manys = manys;
}
}
@Entity public class One { @Id @GeneratedValue private Integer id; private String name; // one to many @OneToMany(cascade = CascadeType.ALL, mappedBy = "one") // @JoinColumn(name = "many_id") private List<Many> manys; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Many類
@Entity
public class Many {
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "one_id")
private One one;
public Integer getId() {
return id;
}
@ManyToMany(mappedBy="manys")
private List<Much> muchs;
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Much> getMuchs() {
return muchs;
}
public void setMuchs(List<Much> muchs) {
this.muchs = muchs;
}
public One getOne() {
return one;
}
public void setOne(One one) {
this.one = one;
}
}
一對一:現有一個single類和One是一對一關系,則只需要在SIngle類中添加如下即可
@OneToOne(fetch = FETCHTYPE.EAGE) private One one;
此時生成的表結構是: 在Single表中有一個one_id字段指向one表的主鍵
一對多: 一個one對應多個many,
首先在一端添加:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "one") //mappedBy = "one" 表示one是一對多管理的被維護端, 既當添加many時順帶添加一個one
private List<Many> manys;
然后再多端添加:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "one_id") // 在多端(從表的外鍵)添加外鍵字段指向一端(主表的主鍵)的主鍵字段 private One one;
此時生成的表結構是:在Many表里有一個one_id外鍵指向一端One
多對多:
拿many和much來說, 他們多對多關系, 我們先確定誰是多放關系的維護端,這里我指定Much為多方關系的維護端。
多對多關系中,hibernate會自動生成中間表。
在Much中添加:
Much類
@ManyToMany
@JoinTable( // JoinTable所在的一端為多方關系的維護端
name = "much_more", // 指定中間表名
joinColumns= {@JoinColumn(name = "much_id", referencedColumnName = "id")}, // 指定當前表在中間表的外鍵名稱和外鍵所指向的當前表主鍵
inverseJoinColumns= {@JoinColumn(name = "more_id", referencedColumnName = "id")} // 指定另一方在中間表的外鍵名稱和外鍵所指向的主鍵
) private List<Many> manys;
然后在多方關系的被維護端Many中添加:
@ManyToMany(mappedBy="manys") // mappedBy指定many為多方關系的被維護端 private List<Much> muchs;
此時生成的表結構是:生成一個中間表叫much_more, 外鍵字段叫much_id,more_id分別指向兩個表的主鍵
歡迎大家指正。
