• mybatis使用collection标签配置某个对象中的List集合类型的属性例子 <collection >


    相关的类还是上篇中的类。

    第一种查询部门的时候将部门对应的所有员工信息也查询出来的方式:

    DepartmentMapper.xml

     
    <!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则  -->
        <resultMap type="com.mybatis.bean.Department" id="MyDept">
            <id column="did" property="id"/>
            <result column="dept_name" property="departmentName"/>
            <!-- 
                collection定义关联集合类型的属性的封装规则 
                ofType:指定集合里面元素的类型
            -->
            <collection property="emps" ofType="com.mybatis.bean.Employee">
                <!-- 定义这个集合中元素的封装规则 -->
                <id column="eid" property="id"/>
                <result column="last_name" property="lastName"/>
                <result column="email" property="email"/>
                <result column="gender" property="gender"/>
            </collection>
        </resultMap>
        <!-- public Department getDeptByIdPlus(Integer id); -->
        <select id="getDeptByIdPlus" resultMap="MyDept">
            SELECT d.id did,d.dept_name dept_name,
                    e.id eid,e.last_name last_name,e.email email,e.gender gender
            FROM tbl_dept d
            LEFT JOIN tbl_employee e
            ON d.id=e.d_id
            WHERE d.id=#{id}
        </select>

    collection分步查询

    先通过部门表的id查出部门信息,再通过员工表的部门id查出所有的员工信息,也就是Department中的private List<Employee> emps;的属性信息

    第二种在查询Department的同时查询出employee的方式:

    DepartmentMapper.xml:首先通过id="getDeptByIdStep"的sql查出部门信息

    再通过collection中的select="com.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"调用EmployeeMapper.xml中的查询语句,column="id"为传递的查询条件的值,也就是将这个值赋给EmployeeMapper.xml中的#{deptId}

    EmployeeMapper.xml

     
        <!-- public List<Employee> getEmpsByDeptId(Integer deptId); -->
        <select id="getEmpsByDeptId" resultType="com.atguigu.mybatis.bean.Employee">
            select * from tbl_employee where d_id=#{deptId}
        </select>
    

      

    最后呢,也就是将查询到的员工信息,即多条Employee记录封装给Departmentemps属性。

    注意:collection的分步查询也是可以延迟加载的,具体配置与上篇中的association一致


    另外,collection元素中还有个fetchType类型,也是用来控制延迟加载的,不过比全局配置的优先级更高。

    fetchType可选的。有效值为 lazy 和 eager。 指定属性后,将在映射中忽略全局配置参数 lazyLoadingEnabled,使用属性的值。
       

    补充:collection中的column属性是数据库中的列名,或着是列的别名,用来传递给select属性所指定语句中的参数,那如果需要传递多个参数该怎么写?

    官方文档:

     
    参考原文:https://www.cnblogs.com/heliusKing/p/11173362.html
     
     
  • 相关阅读:
    If you want the rainbow, you have to deal with the rain.
    Yesterday is history, tomorrow is a mystery, but today is a gift.
    .bashrc修改环境变量文件后ls之类的不能用了
    Flask项目中使用mysql数据库启动项目是发出警告
    flask 编码问题
    flask 密钥问题
    Flask 数据库连接
    查看cpu核的相关信息
    top命令常用
    gluster设置日志级别
  • 原文地址:https://www.cnblogs.com/isme-zjh/p/12496902.html
Copyright © 2020-2023  润新知