当前位置: 移动技术网 > IT编程>数据库>其他数据库 > Mybatis查询延迟加载详解及实例

Mybatis查询延迟加载详解及实例

2017年12月01日  | 移动技术网IT编程  | 我要评论

婆媳的战国时代全集,空白,芭比之歌星公主中文版全集

mybatis查询延迟加载详解及实例

1.1     启用延迟加载

       mybatis的延迟加载是针对嵌套查询而言的,是指在进行查询的时候先只查询最外层的sql,对于内层sql将在需要使用的时候才查询出来。mybatis的延迟加载默认是关闭的,即默认是一次就将所有的嵌套sql一并查了将对象所有的信息都查询出来。开启延迟加载有两种方式。

       第一种是在对应的<collection>或<association>标签上指定fetchtype属性值为“lazy”。如下示例中我们在查询id为selectbyprimarykey的查询时会返回baseresultmap,在baseresultmap中,我们指定了属性“nodes”是一个集合类型的,而且是需要通过id为selectnodes的查询进行查询的,我们指定了该查询的fetchtype为lazy,即延迟加载。

  <resultmap id="baseresultmap" type="com.elim.learn.mybatis.model.syswfprocess">

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

   <result column="template_id" jdbctype="integer" property="templateid" />

   <result column="creator" jdbctype="integer" property="creator" />

   <result column="create_time" jdbctype="timestamp" property="createtime" />

   <collection property="nodes" column="id"

    oftype="com.elim.learn.mybatis.model.syswfnode" select="selectnodes" fetchtype="lazy"/>

  </resultmap>

  <resultmap id="syswfnoderesult" type="com.elim.learn.mybatis.model.syswfnode">

   <id column="id" jdbctype="integer" property="nodeid" />

   <result column="process_id" jdbctype="integer" property="processid" />

   <result column="node_code" jdbctype="varchar" property="nodecode" />

   <result column="node_name" jdbctype="varchar" property="nodename" />

  </resultmap>

  <select id="selectbyprimarykey" parametertype="java.lang.integer"

   resultmap="baseresultmap">

   select

   <include refid="base_column_list" />

   from sys_wf_process

   where id = #{id,jdbctype=integer}

  </select>

  <select id="selectnodes"

   resultmap="syswfnoderesult">

   select id, process_id, node_code, node_name from sys_wf_node

   where process_id=#{id}

  </select>

       第二种是开启全局的延迟加载。通过在mybatis的配置文件的<settings>标签下加上如下配置可开启全局的延迟加载。开启了全局的延迟加载后我们就无需再在各个嵌套的子查询上配置延迟加载了,如果有某一个嵌套的子查询是不需要延迟加载的,可以设置其fetchtype=”eager”。设置在嵌套查询上的fetchtype可以覆盖全局的延迟加载设置。

   <setting name="lazyloadingenabled" value="true"/>

1.2     分析

       mybatis的查询结果是由resultsethandler接口的handleresultsets()方法处理的。resultsethandler接口只有一个实现,defaultresultsethandler。有兴趣的朋友可以去看一下它的源码,看一下它是如何处理结果集的。对于本文的主题,延迟加载相关的一个核心的方法就是如下这个创建返回结果对象的方法。

 private object createresultobject(resultsetwrapper rsw, resultmap resultmap, resultloadermap lazyloader, string columnprefix) throws sqlexception {

  final list<class<?>> constructorargtypes = new arraylist<class<?>>();

  final list<object> constructorargs = new arraylist<object>();

  final object resultobject = createresultobject(rsw, resultmap, constructorargtypes, constructorargs, columnprefix);

  if (resultobject != null && !typehandlerregistry.hastypehandler(resultmap.gettype())) {

   final list<resultmapping> propertymappings = resultmap.getpropertyresultmappings();

   for (resultmapping propertymapping : propertymappings) {

    // issue gcode #109 && issue #149

    if (propertymapping.getnestedqueryid() != null && propertymapping.islazy()) {

     return configuration.getproxyfactory().createproxy(resultobject, lazyloader, configuration, objectfactory, constructorargtypes, constructorargs);

    }

   }

  }

  return resultobject;

 }

        在上面方法中我们可以看到mybatis先是根据正常情况创建一个返回类型对应的对象。当我们的resultmap是包含子查询的时候,其会在我们正常返回类型对象的基础上创建对应的代理对象。对,你没有看错,就是我们的直接结果是代理对象,而不是子查询对应的属性是代理对象。默认是基于javassistproxyfactory类创建的代理对象。可以通过mybatis的全局配置proxyfactory来更改,可选值是cglib和javassist,默认是后者。需要使用cglib代理时注意加入cglib的包。

   <setting name="proxyfactory" value="cglib"/>

       回过头来看我们之前的那个延迟加载的配置,我们的一个查询返回的是syswfprocess类型的对象,其有一个syswfnode集合类型的nodes属性,nodes属性是通过一个子查询查出来的,而且是延迟加载。这个时候我们来进行以下测试。

 @test

  public void testlazyload1() {

   syswfprocessmapper mapper = this.session.getmapper(syswfprocessmapper.class);

   syswfprocess process = mapper.selectbyprimarykey(1);

   system.out.println(process.getclass());

  }
 

       这个时候你会发现,上面的测试代码的输出结果是一个代理类,而不是我们自己的com.elim.learn.mybatis.model.syswfprocess类型。另外如果你启用了日志输出,并且是打印的debug日志,你会看到mybatis是发了两条sql进行查询的。

2016-12-23 15:43:21,131 debug [main] (basejdbclogger.java:145) - ==> preparing: select id, template_id, creator, create_time from sys_wf_process where id = ?

2016-12-23 15:43:21,156 debug [main] (basejdbclogger.java:145) - ==> parameters: 1(integer)

2016-12-23 15:43:21,269 debug [main] (basejdbclogger.java:145) - <==   total: 1

class com.elim.learn.mybatis.model.syswfprocess_$$_jvstc25_0

2016-12-23 15:43:21,271 debug [main] (basejdbclogger.java:145) - ==> preparing: select id, process_id, node_code, node_name from sys_wf_node where process_id=?

2016-12-23 15:43:21,272 debug [main] (basejdbclogger.java:145) - ==> parameters: 1(integer)

2016-12-23 15:43:21,274 debug [main] (basejdbclogger.java:145) - <==   total: 2

 

       但是如果我们把最后一个system.out.println()去掉,也就是说我们只是从数据库中查询出syswfprocess对象,而不使用它的时候,通过查看日志输出你会发现mybatis又只会发送一条sql,即只是查询出syswfprocess的信息。这是为什么呢?

 1.3     aggressivelazyloading

       这是因为当我们启用了延迟加载时,我们的查询结果返回的是一个代理对象,当我们访问该代理对象的方法时,都会触发加载所有的延迟加载的对象信息。这也就可以很好的解释上面的场景。但是如果是这样的设计,貌似mybatis的延迟加载作用不大。但事实并非如此,这只是mybatis的一个默认策略,我们可以通过mybatis的全局配置aggressivelazyloading来改变它,默认是true,表示延迟加载时将在第一次访问代理对象的方法时就将全部的延迟加载对象加载出来。当设置为false时则会在我们第一次访问延迟加载的对象的时候才会从数据库加载对应的数据。注意在延迟对象未从数据库加载出来前,我们对应延迟对象的属性将是null,因为你没有对它赋值。

  <setting name="aggressivelazyloading" value="fasle"/>

1.4     lazyloadtriggermethods

       那如果我们设置了aggressivelazyloading=”false”,但又希望在调用某些方法之前把所有的延迟对象都从数据库加载出来,怎么办呢?这个时候我们可以通过lazyloadtriggermethods参数来指定需要加载延迟对象的方法调用。默认是equals、clone、hashcode和tostring,也就是说我们在调用代理对象的这些方法之前就会把延迟加载对象从数据库加载出来。

   <setting name="lazyloadtriggermethods" value="equals,clone,hashcode,tostring" />

       mybatis延迟加载生成的代理对象的代理过程,可以参考proxyfactory的创建代理对象的过程,以下是基于javassist创建的代理对象的代理过程,基于cglib的代理也是类似的。从下面的代码我们可以看到mybatis的代理对象需要从数据库加载延迟对象时是在目标方法被调用以前发生的,这就可以保证我们的目标方法被调用时延迟加载的对象已经从数据库中加载出来了。

@override

  public object invoke(object enhanced, method method, method methodproxy, object[] args) throws throwable {

   final string methodname = method.getname();

   try {

    synchronized (lazyloader) {

     if (write_replace_method.equals(methodname)) {

      object original = null;

      if (constructorargtypes.isempty()) {

       original = objectfactory.create(type);

      } else {

       original = objectfactory.create(type, constructorargtypes, constructorargs);

      }

      propertycopier.copybeanproperties(type, enhanced, original);

      if (lazyloader.size() > 0) {

       return new javassistserialstateholder(original, lazyloader.getproperties(), objectfactory, constructorargtypes, constructorargs);

      } else {

       return original;

      }

     } else {

      if (lazyloader.size() > 0 && !finalize_method.equals(methodname)) {

       if (aggressive || lazyloadtriggermethods.contains(methodname)) {

        lazyloader.loadall();

       } else if (propertynamer.isproperty(methodname)) {

        final string property = propertynamer.methodtoproperty(methodname);

        if (lazyloader.hasloader(property)) {

         lazyloader.load(property);

        }

       }

      }

     }

    }

    return methodproxy.invoke(enhanced, args);

   } catch (throwable t) {

    throw exceptionutil.unwrapthrowable(t);

   }

  }

 }

       本文是介绍的都是基于<collection>这种关联,其实<association>关联的对象的延迟加载也是一样的,它们的默认策略也是一样的。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网