zoukankan      html  css  js  c++  java
  • collection映射

    讲了many2one和one2many,下面来看看get方法。在之前已经说过,如果是映射单对象,直接使用association来映射。而如果关系 是一个集合,则需要使用collection来描述。和association一样,mybatis不会去管关系是many2many还是 one2many。同理要完成collection映射,也应该有两种方式,1,发送另一条sql;2,内联映射。
    第一种配置方式:
    首先在departmentMapper.xml中添加:
    <select id="get" resultMap="departmentmapper" parameterType="long">
        SELECT * FROM department WHERE id =  #{id}
    </select>
    这只是查询出一条Department,接下来配置resultMap:
    <resultMap type="Department" id="departmentmapper">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="emps" column="id" ofType="Employee" select="cd.itcast.mybatis.mapper.EmployeeMapper.gets" />
    </resultMap>
    这里配置了collection,在collection中:
    1,property:代表集合对应的属性名称为emps;
    2,column:代表one方的id(配合下面的select就清楚了)
    3,ofType:注意,这里的ofType代表的是集合里面的对象类型
    4,select:非常重要的一条,我们先看看这条select对应的映射:
    <select id="gets" resultType="Employee" parameterType="long">
        SELECT * FROM EMPLOYEE WHERE DEPT_ID = #{id}
    </select>
    可以看到,这段sql根据外键从employee表中查询所有的匹配给定的department的employee对象。
    结合select和column,再联想之前的association中的select方式,我们可以明白,mybatis的存放策略为:首先执行查询得 到department结果集,从结果集中得到相关的列,拼装id和name属性。当mybatis运行到emps属性时,会从结果集中,把id得到,并 作为参数传入cd.itcast.mybatis.mapper.EmployeeMapper.gets,并查询到该department对应的 employees,最后把employees设置到Department的emps属性中。
    注意这种方式也遵循延迟加载策略,并且容易产生N+1问题。

    第二种配置方式,内联。
    <select id="get" resultMap="departmentmapper" parameterType="long">
        SELECT d.*,e.id as eid,e.name as ename FROM
        DEPARTMENT d LEFT JOIN EMPLOYEE e ON e.DEPT_ID = d.id WHERE d.id = #{id}
    </select>
        <resultMap type="Department" id="departmentmapper">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
       <collection property="emps" ofType="Employee">
        <id property="id" column="eid"/>
        <result property="name" column="ename"/>
    </collection>
    </resultMap>
    结合前面的解释,应该很好理解了。

    Mybatis学习到此结束,如果你有兴趣,可以参照学习!

  • 相关阅读:
    SQL: 返回刚插入记录的ID 及 output 更新记录时得到更新记录的ID值 .
    asp.net 用伪静态修改webconfig配置文件 .
    Asp.Net : 捕捉和记录网站中出现的所有未处理错误,抛出详细的页面来源和访问ip,调用的接口方法及异常实例(记事本日志,系统日志及数据库日志)
    js闭包(转载) (jquery ajax 异步 多循环运用 )
    c# enum 枚举名称和ID 互换获取.................
    WCF :服务开发与调用的完整示例
    关于DataSet 、 DataTable 、 ArrayList 、 IList 、Array
    Expression Tree不完全入门
    WF4 Beta2:IExecutionProperty的使用
    Groovy 1.8.9, 2.0.7 和 2.1.1 发布
  • 原文地址:https://www.cnblogs.com/shenming/p/3812475.html
Copyright © 2011-2022 走看看