mybatis查询多表有三种方式
《一对多》
1.collection
<!-- 使用collection实现 一对多的 多表查询-->
<resultMap id="ResultMapCollection" type="Clazz">
<id property="cid" column="cid" />
<result property="cname" column="cname" />
<collection property="stus" ofType="Student">
<id property="sid" column="sid" />
<result property="sname" column="sname" />
</collection>
</resultMap>
<select id="selectByCollection" resultMap="ResultMapCollection">
select c.cid,c.cname,s.sid,s.sname from
t_clazz c left join t_stu s
on s.cid=c.cid
where c.cid=#{cid}
</select>
2.分步查
<resultMap id="ResultMapStep1" type="Clazz">
<id property="cid" column="cid"/>
<result property="cname" column="cname"/>
<collection property="stus"
select="com.scidag.mybatis.mapper.StudentMapper.selectByidStep2"
column="cid" />
<!-- 这里有个疑问 就是使用 collection 和association 效果一样 具体有区别吗?-->
</resultMap>
<select id="selectByStep1" resultMap="ResultMapStep1">
select cid,cname from t_clazz where cid =#{cid}
</select>
<!-- 副表的查询 -->
<select id="selectByidStep2" resultType="Student">
select sid,sname from t_stu where cid =#{cid}
</select>
《这是多对一》
1. 使用结果集
<resultMap id="resultMapID" type="pojo类型">
<id property="表1id" column="sid" />
<result property="表1字段" column="sname" />
<result property="表2id" column="cid" />
<result property="表2字段名" column="cname" />
<!-- 这里副表(表2)的字段名和id 要使用 引用对象.字段名 的方式使用 -->
</resultMap>
<select id="来自XxxMapper的接口方法" resultMap="resultMapID">
select s.sid,s.sname,c.cid,c.cname
from t_stu s left join t_clazz c
on s.cid=c.cid
where s.sid =#{sid}
</select>
2. 使用
association
<resultMap id="ResultMapID" type="Student">
<id property="sid" column="sid" />
<result property="sname" column="sname"/>
<association property="clazz" javaType="附表引用对象类型" >
<id property="cid" column="cid"/>
<result property="cname" column="cname"/>
</association>
</resultMap>
<select id="来自xxxMapper 的接口方法" resultMap="ResultMapID">
select s.sid,s.sname,c.cid,c.cname
from t_stu s left join t_clazz c
on s.cid=c.cid
where s.sid =#{sid}
</select>
3.分步查询 多条sql语句 优点 可复用 支持懒加载
<!--对主表的查询 -->
<resultMap id="resultMapid" type="Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<association property="clazz"
select="对下一张表 的Mapper映射文件 接口方法的全限定名称"
column="cid" />
<!--这里的colume 的值要写附表的id 如果写clazz 会找不到副表的数据 -->
</resultMap>
<select id="接口方法名" resultMap="resultMapid">
select sid,sname,cid from t_stu where sid = #{sid}
</select>
<!-- 这是副表的-->
<select id="selectByidStep2" resultType="Clazz">
select cid,cname from t_clazz where cid =#{cid}
</select>