需求:
Course课程实体类中包含教师id,现在希望得到教师的姓名
方法
可以在Course实体类中加一个teacherName字段(数据库中没有此字段)
在resultMap中做如下配置
<resultMap type="com.yimin.course.entity.Course" id="CourseMap">
<result property="id" column="id" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="type" column="type" jdbcType="VARCHAR"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="total" column="total" jdbcType="INTEGER"/>
<result property="choose" column="choose" jdbcType="INTEGER"/>
<result property="teacherId" column="teacher_id" jdbcType="INTEGER"/>
<result property="classroom" column="classroom" jdbcType="VARCHAR"/>
<result property="week" column="week" jdbcType="VARCHAR"/>
<result property="section" column="section" jdbcType="VARCHAR"/>
<result property="college" column="college" jdbcType="VARCHAR"/>
<association property="teacherName" column="teacher_id" select="getTeacherName"/>
</resultMap>
关注最后association,表示teacherName这个字段将通过teacher_id得到,具体查询语句id为getTeacherName,如下所示
<!--学生查询所有课程-->
<select id="getTeacherName" resultType="string">
select name from course.t_user where id = #{teacher_id};
</select>
<select id="selectAllCourse" resultMap="CourseMap">
select * from course.t_course
</select>
然后只需查询course表(使用resultMap)即可,而不需要使用and联表查询