Mybatis---一对一关联表查询

本文探讨了在Mybatis中处理一对一关联查询的两种方法。Method1是直接关联查询,可能导致相同字段名的冲突,而Method2是嵌套查询,能有效避免这类问题。详细解释了每种方法的工作原理,并通过示例展示了如何解决字段名重复导致的异常情况。
摘要由CSDN通过智能技术生成

开发过程中表的关联查询几乎处处可见,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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值