- 一对多的查询
一对多的实现,通常是在一的一方中封装一个List集合,例如
public class Clazz {
private Integer cid;
private String cname;
private List<Student> stus;
// set get⽅法
// 构造⽅法
// toString⽅法
}
一对多的实现通常有两种方式:
- collection
- 分布查询
我们看collection实现一对多查询
首先是Mapper接口
public interface ClazzMapper {
/**
* 根据cid获取Clazz信息
* @param cid
* @return
*/
Clazz selectByCid(Integer cid);
/**
* 根据班级编号查询班级信息。同时班级中所有的学⽣信息也要查询。
* @param cid
* @return
*/
Clazz selectClazzAndStusByCid(Integer cid);
}
映射文件,注意是ofType,表示“集合中的类型”。
<resultMap id="clazzResultMap" 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="selectClazzAndStusByCid" resultMap="clazzResultMap">
select * from t_clazz c join t_student s on c.cid = s.cid where c.cid =
#{cid}
</select>
然后再来看分步查询
与collection不同的是xml映射文件,修改如下
<resultMap id="clazzResultMap" type="Clazz">
<id property="cid" column="cid"/>
<result property="cname" column="cname"/>
<!--主要看这⾥-->
<collection property="stus"
select="com.powernode.mybatis.mapper.StudentMapper.selectByC
id"
column="cid"/>
</resultMap>
<!--sql语句也变化了-->
<select id="selectClazzAndStusByCid" resultMap="clazzResultMap">
select * from t_clazz c where c.cid = #{cid}
</select>
2、多对一查询
使用的关键词是association
//多对一时,使用的标签是association
<resultMap id="accountMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"/>
<association column="uid" property="user" javaType="user" select="dao.IUserDao.findById">
<!-- <id property="id" column="id"></id>-->
<!-- <result property="name" column="name"></result>-->
</association>
</resultMap>
1939

被折叠的 条评论
为什么被折叠?



