简单总结一下,方便以后查看

A表(mxg_category)

 B表(mxg_label)

 B表的category_id 关联A表的ID

通过A表查询B表的id和name,并赋别名 label_id 和label_name

方法一

1、Mapper的接口如下

  List<Category> findCategoryAddLabel();

2、因为A表查询出来要对应多条B表的数据,所以要在A的实体类中添加B的list集合

*
     * @author jiangHaoJie
     * @since 2021-12-08
     * 一个分类可以对应多个标签
     */

    @ApiModelProperty(value = "标签表集合")
    @TableField(exist = false)
    private List<Label> labelList;

3、mapper.xml如下

采用left join   On的方式将两个表连接起来,
 column="label_id" 对应的是数据库查询的字段

 property="id"对应的是实体类的字段

ofType="Label"

ofType 表示返回每个值的类型 比如 List<String> labelIds 就是String类型 在xml 中string小写,

List<Label> labelList 所以用Label,表示实体类所在的地址,因为application.yml中已经配置了mapper路径,所以只用写类名就可以了

<!-- 一般如果没有映射属性名称,直接用property="id"映射就行-->

 <select id="findCategoryAddLabel" resultMap="categoryLabelMap">
        SELECT
            m1.id,
            m1.`name`,
            m2.id label_id,
            m2.`name` label_name
        FROM
            mxg_category m1
        LEFT JOIN mxg_label m2 ON m1.id = m2.category_id
        WHERE m1.`status`=1
    </select>
    <resultMap id="categoryLabelMap" type="Category">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>

        <collection property="labelList" javaType="List" ofType="Label">
            <id column="label_id" property="id"></id>
            <result column="label_name" property="name"></result>
        </collection>
    </resultMap>

方法二

1、mapper的接口如下


    List<Category> findCategoryAddLabel2();

2、mapper.xml 如下

区别是下面collection 中绑定了一个通过Id查询集合的方法

注意resultmap中一定要加上 <id column="id" property="id"></id>,不然主表ID无数据

    <select id="findCategoryAddLabel2" resultMap="categoryLabelMap2">
        SELECT
             id,
             `name`
        FROM  mxg_category
    </select>
    <resultMap  id="categoryLabelMap2" type="Category">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <collection property="labelList" javaType="List"
                    ofType="Label" column="id"
                    select="com.jhj.blog.article.mapper.LabelMapper.labelListByCategoryId"
        >
        </collection>
    </resultMap>

3、绑定的labelListByCategoryId方法,如下

/**
     * 测试一个文章多个标签的联表查询
     */
    List<Label> labelListByCategoryId(@Param("id") String id);

4、实现的XML如下

 <select id="labelListByCategoryId" resultType="Label">
    select * from mxg_label where category_id=#{id}
 </select>

方法一和方法二实现的效果一样

只不过方法二延展性更强

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐