MyBatis中的多表查询操作
连接查询
<!-- 在mybatis—config中
<typeAliases>
<typeAlias type="com.zzb.pojo.User" alias="User"/>
</typeAliases>
定义com.zzb.pojo.User的别名为User,所以可以type="User"
-->
<!-- 连接查询 -->
<resultMap id="userMap" type="User">
<id column="user_id" property="userId"/>
<result column="user_name" property="userName"/>
<result column="user_pwd" property="userPwd"/>
<result column="user_realname" property="userRealName"/>
<result column="user_img" property="userImg"/>
<result column="detail_id" property="detail.detailId"/>
<result column="user_addr" property="detail.userAddr"/>
<result column="user_tel" property="detail.userTel"/>
<result column="user_desc" property="detail.userDesc"/>
</resultMap>
<select id="selectUser" resultMap="userMap">
select user_id,user_name,user_pwd,user_realname,user_img,detail_id,user_addr,user_tel,user_desc
from users u
inner join details d
on u.user_id=d.uid
where user_name=#{userName} and user_pwd=#{userPwd}
</select>
子查询
<!-- 子查询 -->
<resultMap id="userMap" type="User">
<id column="user_id" property="userId"/>
<result column="user_name" property="userName"/>
<result column="user_pwd" property="userPwd"/>
<result column="user_realname" property="userRealName"/>
<result column="user_img" property="userImg"/>
<association property="detail" select="com.zzb.dao.DetailDao.selectDetail" column="user_id"/>
</resultMap>
<select id="selectUser" resultMap="userMap">
select user_id,user_name,user_pwd,user_realname,user_img
from users
where user_name=#{userName} and user_pwd=#{userPwd}
</select>
当一个类中的属性是集合时,用连接查询要使用collection标签来说明
<!-- 连接查询 -->
<resultMap id="classMap" type="Clazz">
<id column="cid" property="classId"/>
<result column="cname" property="className"/>
<result column="cdesc" property="classDesc"/>
<!-- Clazz对象的stus属性是一个list集合,需要使用collection标签 -->
<!-- collection标签的ofType属性声明集合中元素的类型 -->
<collection property="stus" ofType="Student">
<result column="sid" property="stuId"/>
<result column="sname" property="stuName"/>
<result column="sage" property="stuAge"/>
</collection>
</resultMap>
<select id="queryClass" resultMap="classMap">
select cid,cname,cdesc,sid,sname,sage
from classes c
inner join students s
on c.cid=s.scid
where c.cid=#{classId}
</select>