首页 > 解决方案 > 我是mybatis的新手。我想知道mybatis中是如何映射一对多关系的

问题描述

我的项目都是关于使用 spring-mybatis 的 crud 操作。我在 1:M 关系表上执行数据库操作。选择查询返回空列表。在 Employee POJO 类中,我有 List 技能的 setter 和 getter = new ArrayList();

映射器.xml

<resultMap type="employee" id="result">
    <id property="employeeId" column="empId" />
    <result property="firstName" column="firstName" />
    <result property="lastName" column="lastName" />
    <result property="age" column="age" />
    <result property="gender" column="gender" />
    <result property="salary" column="salary" />
    <result property="department" column="department" />
    <result property="state" column="state" />
    <result property="city" column="city" />
    <result property="skillSet" column="skillSet" />
    <result property="address" column="address" />
    <result property="email" column="email" />
    <collection property="skills" ofType="skill" resultMap="skillResult" columnPrefix="skill_"></collection>
</resultMap>

<resultMap type="skill" id="skillResult">
    <id property="skillId" column="skillId"/>
    <result property="skillname" column="skillname"/>
    <result property="empId" column="empId"/>
</resultMap>

<select id="getAllEmployees" resultType="employee" resultMap="result">
    Select e.empid,e.firstname,e.lastname,e.age,e.salary,e.department,e.state,e.city,e.address,e.gender,e.email,s.skillname,s.empId
    from Employee40 e right outer join Skill s on e.empid = s.empid
</select>

标签: spring-mvcmybatisspring-mybatis

解决方案


以下应该可以解决您的问题:

javaType="List"还请在collection-tag中设置属性

<collection
    property="skills"
    javaType="List"
    ofType="skill"
    resultMap="skillResult"
    columnPrefix="skill_"/>

ofType-property 表示Typea Class/的泛型Interface;例如List<?>,您将其实现为ArrayList<Skill>, so javaTypehas to be Listand ofTypemust beskill

columnPrefix您在collection-tag中声明了该属性,但您的 select-statement 有任何以 . 为前缀的列skill_。所以你必须改变/添加类似的东西 s.skillid as skill_id, s.skillname as skill_name, s.empId as skill_empid

<select id="getAllEmployees" resultType="employee" resultMap="result">
    Select
        e.empid,
        e.firstname,
        e.lastname,
        e.age,
        e.salary,
        e.department,
        e.state,
        e.city,
        e.address,
        e.gender,
        e.email,
        s.skillid   as skill_id,
        s.skillname as skill_name,
        s.empId     as skill_empid
    from
        Employee40 e
    right outer join
        Skill s
    on e.empid = s.empid
</select>

columnPrefix在-tag 中声明的声明collection是自动“添加”的,以解决resultMap

例如,select-statement 声明了一个名为/labeled 的列skill_id

collection-tag 告诉 myBatis 使用 acolumnPrefix来解析声明的resultMap

mybatis 结合了-tags, tags, (whatever)columnPrefixcolumn-propertyidresult

columnPrefix="skill_"column="id"成为

skill_id在运行时

<resultMap type="skill" id="skillResult">
    <id
        property="skillId"
        column="id"/>
    <result
        property="skillname"
        column="name"/>
    <result
        property="empId"
        column="empId"/>
</resultMap>

推荐阅读