新的开始之Ibatis集成Ehcache缓存

2 篇文章 0 订阅
2 篇文章 0 订阅

使用版本

ibatis 2.3.4

ehcache 1.2.4

Ibatis提供了集成第三方缓存的接口CacheController

1、编写控制类EhCacheController类:

package com.vprisk.rmplatform.cache.ehcache;
 /**
 * @author name: LXL<br>
 * Written Date: 2013-7-11<br>
 * Written Time: 下午4:56:39<br>
 * Modified By: <br>
 * Modified Date: 
 */


import java.net.URL;
import java.util.Properties;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import com.ibatis.sqlmap.engine.cache.CacheController;
import com.ibatis.sqlmap.engine.cache.CacheModel;

/**
 * EhCache Implementation of the {@link com.ibatis.sqlmap.engine.cache.CacheController} interface to be able to use
 * EhCache as a cache implementation in iBatis. You can configure your cache model as follows, by example, in your
 * sqlMapping files:
 * <cacheModel id="myCache" type="nl.rabobank.springproject.ibatis.EhCacheController" readOnly="true" serialize="false">
 *   <property name="configFile" value="/path-to-ehcache.xml"/>
 * </cacheModel>
 * Alternatively, you can use a type alias in your type attribute and defining the class with a
 * <TypeAlias> declaration, see iBatis documentation on how to do this.
 */
public class EhCacheController implements CacheController {

    /** The EhCache CacheManager. */
    private CacheManager cacheManager;

    /**
     * Flush a cache model.
     * @param cacheModel - the model to flush.
     */
    public void flush(CacheModel cacheModel) {
        getCache(cacheModel).removeAll();
    }

    /**
     * Get an object from a cache model.
     * @param cacheModel - the model.
     * @param key        - the key to the object.
     * @return the object if in the cache, or null(?).
     */
    public Object getObject(CacheModel cacheModel, Object key) {
        Object result = null;
        Element element = getCache(cacheModel).get(key);
        if (element != null) {
            result = element.getObjectValue();
        }
        return result;

    }

    /**
     * Put an object into a cache model.
     * @param cacheModel - the model to add the object to.
     * @param key        - the key to the object.
     * @param object     - the object to add.
     */
    public void putObject(CacheModel cacheModel, Object key, Object object) {
        getCache(cacheModel).put(new Element(key, object));
    }

    /**
     * Remove an object from a cache model.
     * @param cacheModel - the model to remove the object from.
     * @param key        - the key to the object.
     * @return the removed object(?).
     */
    public Object removeObject(CacheModel cacheModel, Object key) {
        Object result = this.getObject(cacheModel, key);
        getCache(cacheModel).remove(key);
        return result;
    }

    /**
     * Configure a cache controller. Initialize the EH Cache Manager as a singleton.
     * @param props - the properties object continaing configuration information.
     */
    public void setProperties(Properties props) {
        URL url = getClass().getResource(props.getProperty("configFile"));
        cacheManager = CacheManager.create(url);
    }

    /**
     * Gets an EH Cache based on an iBatis cache Model.
     * @param cacheModel - the cache model.
     * @return the EH Cache.
     */
    private Cache getCache(CacheModel cacheModel) {
        String cacheName = cacheModel.getId();
        Cache cache = cacheManager.getCache(cacheName);
        return cache;
    }

    /**
     * Shut down the EH Cache CacheManager.
     */
    public void finalize() {
        if (cacheManager != null) {
            cacheManager.shutdown();
        }
    }
}
2、配置使用Ehcache

Ibatis cfg文件中添加:

<sqlMapConfig>
	<!-- 设置使用缓存 -->
	<settings cacheModelsEnabled="true"/>
	<transactionManager type="JDBC" commitRequired="false">
		<dataSource type="SIMPLE">
			<property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver" />
			<property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
			<property name="JDBC.Username" value="VPF_DEMO_DB" />
			<property name="JDBC.Password" value="VPF_DEMO_DB" />
		</dataSource>
	</transactionManager>
	<sqlMap resource="ibatis-sql.xml" />
</sqlMapConfig>
3、SQLMap文件中添加

<sqlMap namespace="SQLMap">
	<!-- 引用缓存控制器 -->
	<typeAlias alias="MapCacheController"
		type="com.vprisk.rmplatform.cache.ehcache.EhCacheController" />
	<cacheModel id="SQLMapCache" type="MapCacheController">
		<!-- 指定ehcache的缓存配置文件 -->
		<property name="configFile" value="/ehcache.xml" />
	</cacheModel>
	<typeAlias alias="User" type="com.vprisk.rmplatform.security.entity.User" />
	<typeAlias alias="Organ"
		type="com.vprisk.rmplatform.security.entity.Organ" />

	<resultMap id="UserLessFieldsResult" class="User">
		<result property="userId" column="USER_ID" />
		<result property="userName" column="USER_NAME" />
		<result property="password" column="PASSWORD" />
	</resultMap>

	<resultMap id="OrganResult" class="Organ">
		<result property="orgId" column="ORG_ID" />
		<result property="orgCode" column="ORG_CODE" />
		<result property="orgName" column="ORG_NAME" />
	</resultMap>

	<select id="selectOrgan" resultMap="OrganResult" parameterClass="java.util.Map" cacheModel="SQLMapCache">
		select * from SYS_SEC_ORGAN
		<dynamic prepend="where">
			<isPropertyAvailable property="orgName">
				<isNotEmpty property="orgName" prepend="and">
					ORG_NAME like
					#orgName#
				</isNotEmpty>
			</isPropertyAvailable>
		</dynamic>
	</select>

</sqlMap>

ehcache.xml配置文件添加:

	 <cache  
	    name="SQLMap.SQLMapCache"  
	    maxElementsInMemory="500"  
	    eternal="false"  
	    timeToLiveSeconds="60"  
	    overflowToDisk="false"  
	    memoryStoreEvictionPolicy="LRU"/> 

JUNIT测试

	  @Test
	  public void testdyna(){
		  try {
			  Organ org = new Organ();
			  org.setOrgName("%aaa%");
			  Map map = pojoToMap(org);
			  List list = sqlMapper.queryForList("selectOrgan",map);
			  System.out.println(list);
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
		  try {
			  Organ org = new Organ();
			  org.setOrgName("%aaa%");
			  Map map = pojoToMap(org);
			  List list = sqlMapper.queryForList("selectOrgan",map);
			  System.out.println(list);
		  } catch (SQLException e) {
			  e.printStackTrace();
		  }
	  }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值