java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis返回结果多重嵌套List

Mybatis返回结果多重嵌套List方式

作者:柿饼zzzz

文章介绍了在实际开发中处理JSON多重嵌套返回格式的方法,通过定义`resultMap`并创建相应的实体类(如`PersonPosGroup`和`PersonData`)来实现自动映射,SQL查询代码会根据层级关系自动映射出查询结果

Mybatis返回结果多重嵌套List

实际开发中,在定义接口的返回格式时往往会遇到返回json多重嵌套的情况:

我们可以通过resultMap自动映射来实现

    <resultMap type="PersonDetailsVo" id="personDetailsMap">
        <result column="sequence_id" property="sequenceId" />
        <collection property="personPosGroup" javaType="java.util.List" ofType="com.ruoyi.project.business.main.domain.PersonPosGroup">
            <result column="camera_id" property="cameraId" />
            <collection property="personData" javaType="java.util.List" ofType="com.ruoyi.project.business.main.domain.PersonData">
                <result column="person_id" property="personId" />
                <result column="position_info" property="positionInfo" />
                <result column="worker_type" property="workerType" />
            </collection >
        </collection >
    </resultMap>

比如这样的resultMap结构就实现了三层嵌套,我们要注意创建PersonPosGroup、PersonData实体类来完成映射。

PersonPosGroup

public class PersonPosGroup implements Serializable {

    private String cameraId;
    private List<PersonData> personData;

    public String getCameraId() {
        return cameraId;
    }

    public void setCameraId(String cameraId) {
        this.cameraId = cameraId;
    }

    public List<PersonData> getPersonData() {
        return personData;
    }

    public void setPersonData(List<PersonData> personData) {
        this.personData = personData;
    }
}

PersonData

public class PersonData implements Serializable {

    private String personId;
    private String workerType;
    private JSONObject positionInfo;

    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }

    public String getWorkerType() {
        return workerType;
    }

    public void setWorkerType(String workerType) {
        this.workerType = workerType;
    }

    public JSONObject getPositionInfo() {
        return positionInfo;
    }

    public void setPositionInfo(String positionInfo) {
        this.positionInfo = JSONObject.parseObject(positionInfo);
    }
}

sql代码

<select id="selectPersonInfoBySequenceId" parameterType="java.util.Map" resultMap="personDetailsMap">
        select
            sequence_id,
            camera_id,
            person_id,
            position_info,
            worker_type
        from video_person_details_info
        where
            1=1
            <if test="video_id != null  and video_id != ''"> and video_id = #{video_id}</if>
            <if test="start_sequence_id != null">
              and sequence_id >= #{start_sequence_id} and  #{end_sequence_id} > sequence_id
            </if>
    </select>

查询数据会根据层级关系自动映射出查询结果

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文