<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.soecode.lyf.dao.ClassDao">
<resultMap type="com.soecode.lyf.entity.Classes" id="ClassResultMap">
<id property="id" column="id"/>
<result property="grade" column="grade"/>
<result property="className" column="class_name"/>
<result property="sumStudent" column="sum_student"/>
<result property="maxStudent" column="max_student"/>
<!-- 用于维护 teacher和class之间一对一的关系 -->
<association property="teacher" column="teacher_id" javaType="com.soecode.lyf.entity.Teacher">
<id property="id" column="id"/>
<result property="teacherName" column="teacher_name"/>
</association>
<!-- 使用一个List<Student>集合属性表示班级拥有的学生
一对多关系
-->
<collection property="students" column="" ofType="com.soecode.lyf.entity.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="gender" property="gender"/>
<result column="birthday" property="birthday"/>
</collection>
</resultMap>
<select id="queryById" parameterType="Long" resultMap="ClassResultMap">
select
*
from
class c,teacher t,student s
where
c.teacher_id = t.id
and
s.class_id = c.id
and
c.id = #{id};
</select>
</mapper>
上面的这种映射配置,查询出某个班级对应的学生列表只有一个,且查询出的id都是输入的参数id,怀疑是xml中
id作用域的问题,导致上面配置的属性id,使用的是同一个,分别更改数据库字段id,实体层id,dao层id
更改后区分,如下所示,问题解决
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.soecode.lyf.dao.ClassDao">
<resultMap type="com.soecode.lyf.entity.Classes" id="ClassResultMap">
<id property="cId" column="c_id"/>
<result property="grade" column="grade"/>
<result property="className" column="class_name"/>
<result property="sumStudent" column="sum_student"/>
<result property="maxStudent" column="max_student"/>
<!-- 用于维护 teacher和class之间一对一的关系 -->
<association property="teacher" column="teacher_id" javaType="com.soecode.lyf.entity.Teacher">
<id property="tId" column="t_id"/>
<result property="teacherName" column="teacher_name"/>
</association>
<!-- 使用一个List<Student>集合属性表示班级拥有的学生
一对多关系
-->
<collection property="students" column="" ofType="com.soecode.lyf.entity.Student">
<id column="s_id" property="sId"/>
<result column="name" property="name"/>
<result column="gender" property="gender"/>
<result column="birthday" property="birthday"/>
</collection>
</resultMap>
<select id="queryById" parameterType="Long" resultMap="ClassResultMap">
select
*
from
class c,teacher t,student s
where
c.teacher_id = t.t_id
and
s.class_id = c.c_id
and
c.c_id = #{id};
</select>
</mapper>