简体   繁体   中英

Using resultmap of mybatis to collect objects into a linkedhashmap

I have two tables: employee_details(department_id, employee_id) & skill_details(employee_id, skill_id). I want to construct LinkedHashMap of Employee_Details objects for each department_id, such that

class Employee_Details {
    long employee_id;
    ArrayList<long> skill_ids;
    // other data & code may be
    ----;
    ----; 
}

How this can be achieved using resultmaps in mybatis

You can use <collection> and <resultMap id="" type="java.util.LinkedHashMap"> like this :

EmployeeDetails.java

public class EmployeeDetails {
    Long employeeId;
    List<SkillDetails> skillDetails;  // mapping snippet is <collection property="skillDetails" ofType="package.SkillDetails" select="selectSkillDetails" column="employee_id">
    // get set
}

FooMapper.xml

  <resultMap id="EmployeeDetailsResultMap" type="java.util.LinkedHashMap" >
    <result column="employee_id" property="employeeId"/>
    <!-- employee_id as foreign key -->
    <collection property="skillDetails" ofType="package.SkillDetails" select="selectSkillDetails" column="employee_id">
        <result property="employeeId" column="employee_id"/>
        <result property="skillId" column="skill_id"/>
    </collection>
  </resultMap>

  <resultMap id="SkillDetailsResultMap" type="java.util.LinkedHashMap" >
    <result column="col1" property="p1" />
    <result column="etc." property="etc." />
  </resultMap>

  <select id="selectSkillDetails" resultMap="SkillDetailsResultMap" >
    SELECT *
      FROM skill_details t1
      where t1.employee_id=#{employee_id}
  </select>

  <select id="selectEmployeeDetails" resultMap="EmployeeDetailsResultMap">
    SELECT *
      FROM employee_details t1
      where t1.department_id=#{department_id}
  </select>

***In the same way, add: **

public class Department {
    Long departmentId;
    List<EmployeeDetails> employeeDetails;
    // get set
}

  <resultMap id="DepartmentsResultMap" type="java.util.LinkedHashMap" >
    <result column="department_id" property="departmentId" />
    <collection property="..." ofType="..." select="selectEmployeeDetails" column="employee_id">
      <result property="employeeId" column="employee_id"/>
      <result property="..." column="..."/>
    </collection>
  </resultMap>

  <select id="selectDepartments" resultMap="..." >
    SELECT *
      FROM ...
  </select>

They are all LinkedHashMap, -_-!
Hope these help...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM