测试表结构
- question表结构
- tag表结构
- question_tag表结构
问题描述
现在有question,tag,question_tag三张表,一个question对应多个tag标签,使用question_tag表将question和tag两个表进行关联。问题是:在调用mybatisplus的service的方法时,默认只会查询question信息,如何查询question的时候将它的tag信息一起查询出来呢?
实现
- 添加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;
}
- 修改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字段