深入iBatis的Cache[转载自javaeye-NetBus 的心得体会]

深入iBatis的Cache[转载自javaeye---NetBus 的心得体会]


关键字: ibatis cache

概述
  • iBatis对查询结果集进行本地缓存。
  • Cache 的key由haskcode、checksum、查询参数、sqlmap Id、sql语句、调用方法名等构成。由此可以看出,不同的参数会有不同的Key。注意,他不是以查询参数的Class的hashcode或 toString方法作为key的一部分,而是以在sqlmap使用的变量的集合。
  • queryForObject和queryForList都可以缓存。其它片断不支持。
  • 可以设定为定时刷新或受条件触发刷新Key。如:在执行Update的时候,可以刷新Cache。
    刷新Cache时,无法手动控制刷新单条记录。只能刷新该Cache ID的全部Cache。
  • 目前有4种Cache实现,但是无法自定义扩展Cache。
  • Cache的数量可以指定。
  • Cache的put和get方法内有同步,外部无。所以同一参数同时查询时,Cache是不能命中的。在有一个结果put到Cache后,后续查询才能命中。
相关示例代码如下: Xml代码 深入iBatis的Cache[转载自javaeye-NetBus 的心得体会]
  • <cachemodel< font=""> id ="lruCache" type ="LRU" serialize ="true" readOnly ="false" >
  • <property< font=""> name ="reference-type" value ="WEAK" />
  • <flushonexecute< font=""> statement ="insertAccount" />
  • <flushonexecute< font=""> statement ="updateAccount" />
  • <flushonexecute< font=""> statement ="deleteAccountById" />
  • </cachemodel>
  • <select< font=""> id ="selectAccountById" parameterClass ="int" resultClass ="Account" cacheModel ="lruCache" >
  • select ACC_ID as id, ACC_FIRST_NAME as firstName,
  • ACC_LAST_NAME as lastName, ACC_EMAIL as emailAddress from ACCOUNT where ACC_ID = #id#
  • <update< font=""> id ="updateAccount" parameterClass ="Account" >
  • update ACCOUNT set ACC_FIRST_NAME =#firstName# , ACC_LAST_NAME = #lastName# , ACC_EMAIL =#emailAddress# where ACC_ID = #id#
  • </update>
  • <cachemodel id="lruCache" type="LRU" serialize="true" readonly="false"> <property name="reference-type" value="WEAK"> <flushonexecute statement="insertAccount"> <flushonexecute statement="updateAccount"> <flushonexecute statement="deleteAccountById"> </cachemodel> <update id="updateAccount" parameterclass="Account"> update ACCOUNT set ACC_FIRST_NAME=#firstName# , ACC_LAST_NAME = #lastName# , ACC_EMAIL =#emailAddress# where ACC_ID = #id# </update>

    Cache规则
    • Type 目前有4种实现。建议用LRU或者OsCache
    • readOnly,表示Cache对象是否只读。False,表示外部更改cache内容无效。
    • Serialize,是否序列化。true,表示存贮到cache中的是系列化后的对象。
    • 组合:
      • readOnly=false, Serialize=false:Cache Session有效。如:1+n时,下次1+n将会失效。 不系列化,外部更改有效。
      • readOnly=true, Serialize=false:所有session共享Cache,取出时实例是同一个。不系列化,外部更改有效。默认的
      • readOnly=false, Serialize=true:所有session共享Cache,取出时实例不一样,但是内容一样。 系列化,外部更改无效
      • readOnly=true, Serialize=true: 同默认效果一样。
      • 看得出,主要是通过系列化来保证外部更改属性后不影响其它session的取出的结果。
    4种Cache实现
    1. LRU,最后使用的排到前面。Cache溢出时,最远被使用的就被clear。
    2. FIFO,先进先出。
    3. Memory,内存引用。该实现无数量限制。前两种是基于jvm实现。
      • WEAK,产生内存回收动作时,失效。
      • SOFT,内存不足时,失效。
      • STRONG,显式刷新时,失效。
    4. OsCache(支持分布式)。通过oscahce.properties控制。
    适应范围
    1. 频繁查询,很少更改的内容。如:分类等。
    2. 1+n查询。n是父类,数据量较少。如:查询Spu信息时,同意需要获得其品类信息。
    3. 效率低,执行频率高的SQL。如统计一类的SQL。
    4. 有了Cache机制后,1+n不再可怕。