mybatis plus多表关联数据查询

测试表结构
  1. question表结构
    问题表
  2. tag表结构
    在这里插入图片描述
  3. question_tag表结构
    在这里插入图片描述
问题描述

现在有question,tag,question_tag三张表,一个question对应多个tag标签,使用question_tag表将question和tag两个表进行关联。问题是:在调用mybatisplus的service的方法时,默认只会查询question信息,如何查询question的时候将它的tag信息一起查询出来呢?

实现
  1. 添加tags字段的ArrayList用于存放tag信息,并添加@TableField(exist = false)注解,表示tags字段不在question表中。@TableName(value =“question”,resultMap = “BaseResultMap”)中指定resultMap,这里BaseResultMap配置在mapper文件中,下面说如何配置。
@TableName(value ="question",resultMap = "BaseResultMap")
@Data
public class Question implements Serializable {
    @TableId(type = IdType.AUTO)
    private Integer id;
	private String title;
	private String content;
	private Integer score;
	@TableField(exist = false)
    private ArrayList<Tag> tags;
}
  1. 修改Mappe中BaseResultMap配置,添加对应实体类中添加的tags字段。select=“getTagsByQuestionId"表示查询tag用到的sql语句。column中配置字段的对应关系,比如column=”{question_id=id}"中question_id对应查询tag的sql语句中的入参#{question_id},id对应的是question类的字段id。
    <resultMap id="BaseResultMap" type="com.sundae.questionserver.entity.Question">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="title" column="title" jdbcType="VARCHAR"/>
            <result property="content" column="content" jdbcType="VARCHAR"/>
            <result property="score" column="score" jdbcType="INTEGER"/>
            <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
            <result property="createUserId" column="create_user_id" jdbcType="VARCHAR"/>
            <collection property="tags" column="{question_id=id}" select="getTagsByQuestionId"></collection>
    </resultMap>
    
    <!-- 查询tag的sql语句,根据question的id查询出该question对应的tag -->
    <select id="getTagsByQuestionId" resultType="com.sundae.questionserver.entity.Tag">
        select t.id,t.tag_name from tag t where id in
            (
                select qt.tag_id from question_tag qt where qt.question_id = #{question_id}
            )
    </select>

这样使用QuestionService,public interface QuestionService extends IService 这个类查询出来的question都默认添加有tags字段

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值