mybatis 返回的一对多collection对象包含另一个对象

java | 2021-03-22 11:16:48 | 阅读 142 次 | 评论(0)

对象1

package com.project.dto;

import lombok.Data;

import java.util.List;

@Data
public class DeptDTO {

    private String deptCode;
    private String deptName;
    private String companyName;
    private List<UserDTO> children;
}
对象2
package com.project.dto;

import lombok.Data;

@Data
public class UserDTO {
    private String id;
    private String name;
}

resultMap 映射

  <resultMap id="DeptUserResultMap" type="com.project.dto.DeptDTO">
    <result column="deptCode" jdbcType="VARCHAR" property="deptCode"/>
    <result column="companyName" jdbcType="VARCHAR" property="companyName"/>
    <result column="deptName" jdbcType="VARCHAR" property="deptName"/>
    <collection property="children" ofType="com.project.dto.UserDTO">
      <result column="userId" property="id"/>
      <result column="userName" property="name"/>
    </collection>
  </resultMap>

mybatis sql编写

<select id="selectByCompanyId" resultMap="DeptUserResultMap">
    select
    a.user_id as userId,
    d.name as userName,
    b.id as deptCode,b.department_name as deptName,b.parent_id,
    c.company_name as companyName
    from employee_detail a
    left join base_department b on FIND_IN_SET(b.id,a.dept_id)
    left join base_company c on a.company_id = c.id
    inner join base_people d on a.people_id = d.id and d.del_flag = 0
    where 1=1
    <if test="companyId != null">
      and a.company_id = #{companyId}
    </if>

    <if test="userName != null">
      and a.user_name like concat('%',#{userName},'%')
    </if>
    group by a.user_id,b.id
  </select>
返回结果



{
    "code": 0,
    "msg": null,
    "count": 0,
    "data": [
        {
            "deptCode": null,
            "deptName": null,
            "companyName": "***公司",
            "children": [
                {
                    "id": "2222",
                    "name": "test"
                }
            ]
        }
    ]
}
说明:返回结果可以是查询某公司的成员,公司与成员为一对多关系,可以查询多个公司;或是目录权限查询

需要拓展可以参考https://blog.csdn.net/BushQiang/article/details/100707245

**************************************转载注明出处,谢谢*****************************************

文章评论,共0条
游客请输入验证码