Mybatis关联映射

Mybatis关联映射

一、Mybatis的关联映射有两种不同的实现形式:

1.嵌套查询:通过执行另一个SQL映射语句来返回关联数据(查询两次)

**2.嵌套结果查询:**执行一个表关联查询SQL,然后将查询结果映射成关联对象(查询一次)

1.一对一映射

create table t_teacher(
t_id int(4) primary key auto_increment,
t_name varchar(10) not null
);

create table t_class(
c_id int(2) primary key auto_increment,
c_name varchar(20),
teacher_id int(4)
);

alter table t_class add constraint fk_teacher_id foreign key(teacher_id)
references t_teacher(t_id);

insert into t_teacher(t_name) values("张三丰");
insert into t_teacher(t_name) values("孙悟空");
insert into t_class(c_name,teacher_id) values("三年二班",2);
insert into t_class(c_name,teacher_id) values("五年六班",1);

一对一的嵌套查询

<!--一对一的嵌套查询-->
	<resultMap id="teacherMapOne" type="Teacher">
		<id property="id" column="t_id"/>
		<result property="name" column="t_name"/>
		<association property="cls" column="t_id" select="findClass"/>
	</resultMap>
	<select id="findTeacherByIdOne" parameterType="int" resultMap="teacherMapOne">
		select * from t_teacher where t_id=#{id};
	</select>

	<resultMap id="classMap" type="Class">
		<id property="id" column="c_id"/>
		<result property="name" column="c_name"/>
		<result property="teacherId" column="teacher_id"/>
	</resultMap>
	<select id="findClass" parameterType="int" resultMap="classMap">
		select * from t_class where teacher_id=#{id};
	
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值