开发过程中表的关联查询几乎处处可见,Mybatis对关联查询可进行很好的处理,下面主要记录下一对一关联表的查询。
此处用到两个实体类及其关系如下:
School与President为一对一关联,设计javaBean:
//校长
public class President {
private int id;
private String name;
@Override
public String toString() {
return "President [id=" + id + ", name=" + name + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
和
public class School {
private int id;
private String name;
private President president;
@Override
public String toString() {
return "School [id=" + id + ", name=" + name + ", president=" + president + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public President getPresident() {
return president;
}
public void setPresident(President president) {
this.president = president;
}
}
创建数据表:
create table president1(
p_id int not null auto_increment primary key,
p_name varchar(50) not null
);
insert into president1(p_name) values('lily'),('Tom');
create table school1(
s_id int not null auto_increment primary key,
s_name varchar(50) not null,
president_id int not null,
constraint foreign key(president_id) references president1(p_id)