有班级表,老师表,要求给定班级id查出班级信息和班级对应的老师信息
1、使用嵌套结果方式
sql语句:
<select id="findClasses" parameterType="int" resultMap="findClassesMap">
select c.*,t.t_name from classes c,teacher t where c.t_id = t.t_id and c.c_id =#{id} ;
</select>
<resultMap type="Classes" id="findClassesMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" javaType="Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>
</resultMap>
2、使用嵌套查询方式
select * from class where c_id = #{id}
select * from teacher where t_id = #{teacher_id} //使用上一个查询的结果teacher_id
<select id="findClasses2" parameterType="int" resultMap="findClasses2Map">
select * from classes where c_id=#{id}
</select>
<resultMap type="Classes" id="findClasses2Map">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" select="findTeacher" column="t_id">
</association>
</resultMap>
<select id="findTeacher" parameterType="int" resultType="Teacher">
select t_id id,t_name name from teacher where t_id = #{t_id}
</select>
在association节点中配置两个属性column指上次查询结果哪个字段作为下一次查询的参数条件 select指对应的查询