使用mybatis的resultmap将对象收集到linkedhashmap中

时间:2014-09-09 19:07:03

标签: java mybatis ibatis linkedhashmap

我有两张桌子: employee_details(department_id,employee_id)& skill_details(employee_id,skill_id)。 我想为每个department_id构建Employee_Details对象的LinkedHashMap, 这样

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

如何使用mybatis中的结果图

实现这一目标

1 个答案:

答案 0 :(得分:0)

您可以像这样使用<collection><resultMap id="" type="java.util.LinkedHashMap">

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>

***以同样的方式,添加:**

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>

它们都是LinkedHashMap,-_-!
希望这些帮助......