mybatis-plus 实现一对多查询,返回VO对象某个字段为List

类关系

Animal类下包含一个List

@Data
@TableName("animal")
public class Animal {
    @TableId
    private String id;
    private Integer type;
    private List<Dog> dogList;
}

@Data
@TableName("dog")
public class Dog {
    @TableId
    private String id;
    private Integer type;
    private String name;
    private Integer age;
    private String color;
}

表中数据:
mybatis-plus 实现一对多查询,返回VO对象某个字段为List_第1张图片
mybatis-plus 实现一对多查询,返回VO对象某个字段为List_第2张图片

问题

期望获得:


    {
        "id": "1",
        "type": 1,
        "dogList": [
            {
                "id": "1",
                "type": "1",
                "name": "dogA",
                "age": 3,
                "color": "black"
            },
            {
                "id": "2",
                "type": "1",
                "name": "dogB",
                "age": 4,
                "color": "red"
            }
        ]
    }

实际查询:
当用sql查询时animal和dog是一对多关系,会获得两条数据:
mybatis-plus 实现一对多查询,返回VO对象某个字段为List_第3张图片

mybatis处理

1、写resultMap,注意collection标签还有两表重名字段要使用别名

collection 标签内放List下Dog类的字段,重名字段id和type如果不使用别名会报 duplicate column name …的错误。

    <resultMap id="AnimalMap" type="org.example.VO.Animal">
        <id column="id" property="id" />
        <result column="type" property="type" />
        
        <collection property="dogList" ofType="com.mylearn.heimaspringboot.domain.Dog">
            <id column="dog_id" property="id" />
            <result column="dog_type" property="type" />
            <result column="name" property="name" />
            <result column="age" property="age" />
            <result column="color" property="color" />
        collection>
    resultMap>

2、sql

    <select id="findAnimal" resultMap="AnimalMap">
        SELECT a.id,a.type,
                d.id dog_id, d.type dog_type, d.name, d.age, d.color
        FROM animal a
            LEFT JOIN dog d ON a.type=d.type
    select>

调接口查询可以发现数据已拼接好

[
    {
        "id": "1",
        "type": 1,
        "dogList": [
            {
                "id": "1",
                "type": "1",
                "name": "dogA",
                "age": 3,
                "color": "black"
            },
            {
                "id": "2",
                "type": "1",
                "name": "dogB",
                "age": 4,
                "color": "red"
            }
        ]
    }
]

备注

mybatis中collection和association的作用以及用法

你可能感兴趣的:(java,list,数据结构)