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};