簡體   English   中英

如何使用 mybatis 獲取 map JSON_ARRAYAGG 結果

[英]How to map JSON_ARRAYAGG results with mybatis

我不能 map JSON_ARRAYAGG function 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>

用戶VO model:

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

圖片VO model:

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

調用 API 的結果:

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

如您所見, pictures只有一個id可以正確為 map。 假設pictures中有2個結果,如果我直接執行sql,這里只返回1個。

你應該設置你的方法的 ("findUserById") 返回類型 List 並且 MyBatis 會自動完成。 嘗試在mapper界面中編寫:

List<UserVo> findUserById();

MyBatis returns Java objects not JSON, so it may be your 'API' that converts the Java objects into 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

使用類型處理程序。 例如:

<resultMap id="userMap" type="UserVO">
        <id property="id" column="id" />
        <result property="username" column="username"/>
        <result property="pictures" column="pictures" 
         typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler"
        />
    </resultMap>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM