mybatis多表查询(只需要另一个表中的一个字段)

需求:

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联表查询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值