Mybatis第三讲——关联一对一 (1)

本文详细介绍了在MyBatis中如何通过XML配置实现学生信息表与地址表的关联映射,包括定义Address和Student类,创建关联的ResultMap,以及通过SQL查询结合两表数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis第二讲——熟悉使用XML配置SQL映射器

 这讲主要是针对两张表,一张学生信息表t_student,一张地址表t_address:

t_student中的addressId字段对应于t_address中的id,但是两张表之间并没有物理上的关联。我们只是人为的把字段添加上去了而已。

 

工程结构:

与第二讲相比,增加了model下的Address.java 文件:

package com.java1234.model;

public class Address {

	private Integer id;
	private String sheng;
	private String shi;
	private String qu;
	
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getSheng() {
		return sheng;
	}
	public void setSheng(String sheng) {
		this.sheng = sheng;
	}
	public String getShi() {
		return shi;
	}
	public void setShi(String shi) {
		this.shi = shi;
	}
	public String getQu() {
		return qu;
	}
	public void setQu(String qu) {
		this.qu = qu;
	}
	@Override
	public String toString() {
		return "Address [id=" + id + ", sheng=" + sheng + ", shi=" + shi + ", qu=" + qu + "]";
	}
	
	
}

StudentMapper.java中新增接口:

 

StudentMapper.xml中新增如下代码段:

<resultMap type="Address" id="addressResult">
	 <result property="id" column="id"/>
		<result property="sheng" column="sheng"/>
		<result property="shi" column="shi"/>
		<result property="qu" column="qu"/> 
	</resultMap>
	
	<resultMap type="Student" id="StudentResult">
		<id property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="age" column="age"/>
		
		<!-- <result property="address.id" column="addressId"/>
		<result property="address.sheng" column="sheng"/>
		<result property="address.shi" column="shi"/>
		<result property="address.qu" column="qu"/> -->
		
		<association property="address" resultMap="addressResult"/>
	</resultMap> 
	
	<select id="getAllStudents" resultMap="StudentResult">
	select * from t_student 
	</select>
	
	<select id="findStudentWithAddress" resultMap="StudentResult" parameterType="Integer">
	select * from t_student t1,t_address t2 where t1.addressId=t2.id and t2.id=#{id} 
	</select>

测试:

输出结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员资料站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值