使用一个例子来表明一对多和多对一的关系(国家、省份和城市之间的关系)
一个国家有多个省份(一对多),多个省份属于一个国家(多对一)
一个省份有多个城市(一对多),多个城市属于一个省份(多对一)
首先,创建三个实体类分别是:Nation(国家),Province(省份),City(城市)
Ont-To-Many:定义多端Set集合,需要实例化HashSet
Many-To-Ont:定义一端对象
Nation(国家)实体类:
public class Nation {
private String nid;
private String nname;
private Set<Province> sp = new HashSet<>();
public Nation() {
super();
// TODO Auto-generated constructor stub
}
public Nation(String nid, String nname, Set<Province> sp) {
super();
this.nid = nid;
this.nname = nname;
this.sp = sp;
}
public String getNid() {
return nid;
}
public void setNid(String nid) {
this.nid = nid;
}
public String getNname() {
return nname;
}
public void setNname(String nname) {
this.nname = nname;
}
public Set<Province> getSp() {
return sp;
}
public void setSp(Set<Province> sp) {
this.sp = sp;
}
@Override
public String toString() {
return "Nation [nid=" + nid + ", nname=" + nname + "]";
}
Province(省份)实体类:
public class Province {
private String pid;
private String pname;
private Nation nation;
private Set<City> sc = new HashSet<>();
public Province() {
super();
// TODO Auto-generated constructor stub
}
public Province(String pid, String pname, Nation nation, Set<City> sc) {
super();
this.pid = pid;
this.pname = pname;
this.nation = nation;
this.sc = sc;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Nation getNation() {
return nation;
}
public void setNation(Nation nation) {
this.nation = nation;
}
public S