MyBatis框架

4.7.5 collection

  • POJO中的属性可能会是一个集合对象,我们可以使用联合查询,并以级联属性的方式封装对象.使用collection标签定义对象的封装规则

public class Department {

         private Integer id ;

         private String departmentName ;

         private List<Employee> emps ;

}

  • Collection

<select id="getDeptAndEmpsById" resultMap="myDeptAndEmps">

                   SELECT d.id did, d.dept_name ,e.id eid ,e.last_name ,e.email,e.gender

                   FROM tbl_dept d  LEFT OUTER JOIN tbl_employee e ON  d.id = e.d_id

                   WHERE d.id = #{id}

         </select>

         <resultMap type="com.atguigu.mybatis.beans.Department" id="myDeptAndEmps">

                   <id column="did" property="id"/>

                   <result column="dept_name" property="departmentName"/>

                   <!--

                            property: 关联的属性名

                            ofType: 集合中元素的类型

                    -->

                   <collection property="emps"  ofType="com.atguigu.mybatis.beans.Employee">

                            <id column="eid" property="id"/>

                            <result column="last_name" property="lastName"/>

                            <result column="email" property="email"/>

                            <result column="gender" property="gender"/>

                   </collection>

</resultMap>

 

       4.7.6 collection 分步查询

  • 实际的开发中,对于每个实体类都应该有具体的增删改查方法,也就是DAO层, 因此

对于查询部门信息并且将对应的所有的员工信息也查询出来的需求,就可以通过分步的方式完成查询。

  • 先通过部门的id查询部门信息
  • 再通过部门id作为员工的外键查询对应的部门信息.

<select id="getDeptAndEmpsByIdStep" resultMap="myDeptAndEmpsStep">

                 select id ,dept_name  from tbl_dept where id = #{id}

          </select>

          <resultMap type="com.atguigu.mybatis.beans.Department" id="myDeptAndEmpsStep">

                 <id column="id" property="id"/>

                 <result column="dept_name" property="departmentName"/>

                 <collection property="emps"

                                    select="com.atguigu.mybatis.dao.EmployeeMapper.getEmpsByDid"

                                    column="id">

                 </collection>

 </resultMap>

 

       4.7.7 collection 分步查询使用延迟加载

       4.7.8 扩展: 分步查询多列值的传递

  • 如果分步查询时,需要传递给调用的查询中多个参数,则需要将多个参数封装成

Map来进行传递,语法如下: {k1=v1, k2=v2....}

  • 在所调用的查询方,取值时就要参考Map的取值方式,需要严格的按照封装map

时所用的key来取值.

 

 

       4.7.9 扩展: association 或 collection的 fetchType属性

  • 在<association> 和<collection>标签中都可以设置fetchType,指定本次查询是否要使用延迟加载。默认为 fetchType=”lazy” ,如果本次的查询不想使用延迟加载,则可设置为

fetchType=”eager”.

  • fetchType可以灵活的设置查询是否需要使用延迟加载,而不需要因为某个查询不想使用延迟加载将全局的延迟加载设置关闭.