mybatis 关联查询之association定义关联对象封装规则

来源:互联网 发布:java基本类型内存分配 编辑:程序博客网 时间:2024/06/08 10:57

1.使用association嵌套结果集实现关联查询:代码如下

 <resultMap id="getPerson" type="mybatis_02.Person">        <id property="id" column="id" />        <result property="name" column="name"/>        <result property="gender" column="gender"/>        <association property="department" javaType="mybatis_02.Department">            <result property="id" column="deptno"/>            <result property="name" column="name"/>        </association>    </resultMap>

对应的sql语句

<select id="getPersonById" resultMap="getPerson">    select * from person where id=#{id}</select>

其中 deptno和name是department表中的属性,而department也是已经定义好的javabean,这样就可以使用association标签来定义封装规则

2.使用association分步查询实现关联查询:简单的来说就是在查询时使用association再调用别的查询语句来查出其他结果,并用association定义封装规则,语义说的不是很清晰,代码如下:

<resultMap type="mybatis_02.Person" id="getPersonStep">        <id column="id" property="id"/>        <result column="name" property="name"/>        <result column="gender" property="gender"/>        <association property="department" javaType="mybatis_02.Department" select="mybatis_02.DepartmentMapper.getDepartmentById" column="id">            <result column="deptno" property="id"/>            <result column="name" property="name"/>        </association></resultMap>

对应的sql语句如下:

<select id="getPersonByIdStep" resultMap="getPersonStep">    select * from person where id=#{id}</select>

其中association标签中的select标签指的是调用的哪个查询语句,column标签则是表示调用该查询语句时传入的参数是什么。
上述代码相当于先查出一个人的所有信息,然后通过查出的信息中这个人所在的部门编号调用getDepartmentById()方法查出这个人所在部门的信息,封装成一个resultmap返回回来。这样相当于分步查询,先查处这个人的信息,再查出这个人所在的部门信息。
总结:查询时相当于向数据库发送了两条sql语句。

3.association分步查询之延迟加载:
所谓延迟加载,也叫作按需加载,有些时候,我们只需查询一个人的信息而不需要查询这个人的部门信息,而有时则需要查询此人的信息以及此人所在部门的信息,那么这个时候我们就可以使用延迟加载,开启延迟加载之后,当我们需要用到此人的部门信息时,才会发送查询部门信息的sql语句,如果不需要用到部门的有关信息时,则不会发送查询部门信息的sql语句,这样大大的减少了服务器的负担。开启延迟加载的方法如下,在mybatis-config.xml(mybatis全局配置文件)中加入以下代码

<settings>    <setting name="lazyLoadingEnabled" value="true"/>    <setting name="aggressiveLazyLoading" value="false"/></settings>
阅读全文
0 0
原创粉丝点击