0

我无法从JSON_ARRAYAGG function.

mybatis 映射器:

<mapper namespace="com.test.mapper.UserEntityMapper">
    <resultMap id="userMap" type="UserVO">
        <id property="id" column="id" />
        <result property="username" column="username"/>
        <collection property="pictures" ofType="PictureVO">
            <id property="id" column="id" />
            <result property="location" column="location" />
        </collection>
    </resultMap>
    <select id="findUserById" parameterType="map" resultMap="userMap">
        SELECT
        users.id,
        users.username,
        JSON_ARRAYAGG(
            JSON_OBJECT(
                "id",
                pic.id,
                "location",
                pic.location
            ) 
        ) AS pictures
        FROM
            users
            LEFT JOIN pictures pic ON users.id = pic.user_id 
        WHERE
            users.id = 1
    </select>
</mapper>

UserVO 型号:

@Getter
@Setter
@NoArgsConstructor
public class UserVO {
    private Long id;
    private String username;
    private List<PictureVO> pictures;
}

图片VO型号:

@Getter
@Setter
@NoArgsConstructor
public class PictureVO {
    private Long id;
    private String location;
}

调用 API 的结果:

{
    "id": 1,
    "username": "connor",
    "pictures": [
        {
            "id": 1,
            "location": null
        }
    ]
}

如您所见,pictures只有一个id可以正确映射。假设有2个结果pictures,如果我直接执行sql,这里只返回1个。

4

2 回答 2

0

MyBatis 返回 Java 对象而不是 JSON,因此可能是您的“API”将 Java 对象转换为 JSON。
如果我是对的,你只需要做正常的 MyBatis 映射。

像这样的东西:

<resultMap id="userMap" type="UserVO">
  <id property="id" column="id" />
  <result property="username" column="username"/>
  <collection property="pictures" ofType="PictureVO">
    <id property="id" column="picture_id" />
    <result property="location" column="location" />
  </collection>
</resultMap>

<select id="findUserById" parameterType="map" resultMap="userMap">
  SELECT
    users.id,
    users.username,
    pic.id picture_id,
    pic.location
  FROM
    users
    LEFT JOIN pictures pic ON users.id = pic.user_id
  WHERE
    users.id = 1
</select>

请注意,pic.id需要一个别名来区分users.id结果集中的列。

于 2021-01-05T22:27:42.950 回答
0

你应该设置你的方法的 ("findUserById") 返回类型 List 并且 MyBatis 会自动完成。尝试在mapper界面中编写:

List<UserVo> findUserById();
于 2021-01-05T11:01:20.877 回答