mybatis和ehcache整合
生活随笔
收集整理的這篇文章主要介紹了
mybatis和ehcache整合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace命名空間,為了對sql語句進行隔離,方便管理 ,mapper開發dao方式,使用namespace有特殊作用
mapper代理開發時將namespace指定為mapper接口的全限定名-->
<mapper namespace="cn.learn.mybatis.mapper.UserMapper">
<!-- 在mapper.xml文件中配置很多的sql語句,執行每個sql語句時,封裝為MappedStatement對象
mapper.xml以statement為單位管理sql語句--><!-- 開啟二級緩存 --><!-- 單位:毫秒 --><cache type="org.mybatis.caches.ehcache.EhcacheCache"><property name="timeToIdleSeconds" value="12000"/><property name="timeToLiveSeconds" value="3600"/><!-- 同ehcache參數maxElementsInMemory --><property name="maxEntriesLocalHeap" value="1000"/><!-- 同ehcache參數maxElementsOnDisk --><property name="maxEntriesLocalDisk" value="10000000"/><property name="memoryStoreEvictionPolicy" value="LRU"/></cache><!-- 將用戶查詢條件定義為sql片段建議對單表的查詢條件單獨抽取sql片段,提高公用性注意:不要將where標簽放在sql片段--><sql id="query_user_where"><!-- 如果 userQueryVo中傳入查詢條件,再進行sql拼接--><!-- test中userCustom.username表示從userQueryVo讀取屬性值--><if test="userCustom!=null"><if test="userCustom.username!=null and userCustom.username!=''">and username like '%${userCustom.username}%'</if><if test="userCustom.sex!=null and userCustom.sex!=''">and sex = #{userCustom.sex}</if><!-- 還有很的查詢條件 --></if><if test="ids!=null"><!-- 根據id集合查詢用戶信息 --><!-- 最終拼接的效果:SELECT id ,username ,birthday FROM USER WHERE username LIKE '%小明%' AND id IN (16,22,25)collection:集合的屬性open:開始循環拼接的串close:結束循環拼接的串item:每次循環取到的對象separator:每兩次循環中間拼接的串--><foreach collection="ids" open=" AND id IN ( " close=")" item="id" separator=",">#{id}</foreach><!-- SELECT id ,username ,birthday FROM USER WHERE username LIKE '%小明%' AND (id = 16 OR id = 22 OR id = 25) <foreach collection="ids" open=" AND ( " close=")" item="id" separator="OR">id = #{id}</foreach>--></if></sql><!-- 定義resultMap,列名和屬性名映射配置id:mapper.xml中的唯一標識 type:最終要映射的pojo類型--><resultMap id="userListResultMap" type="user" ><!-- 列名id_,username_,birthday_id:要映射結果集的唯 一標識 ,稱為主鍵column:結果集的列名property:type指定的哪個屬性中--><id column="id_" property="id"/><!-- result就是普通列的映射配置 --><result column="username_" property="username"/><result column="birthday_" property="birthday"/></resultMap><!-- 根據id查詢用戶信息 --><!-- id:唯一標識 一個statement#{}:表示 一個占位符,如果#{}中傳入簡單類型的參數,#{}中的名稱隨意parameterType:輸入 參數的類型,通過#{}接收parameterType輸入 的參數resultType:輸出結果 類型,不管返回是多條還是單條,指定單條記錄映射的pojo類型--><select id="findUserById" parameterType="int" resultType="user" >SELECT * FROM USER WHERE id= #{id}</select><!-- 根據用戶名稱查詢用戶信息,可能返回多條${}:表示sql的拼接,通過${}接收參數,將參數的內容不加任何修飾拼接在sql中。--><select id="findUserByName" parameterType="java.lang.String" resultType="cn.learn.mybatis.po.User">select * from user where username like '%${value}%'</select><!-- 自定義查詢條件查詢用戶的信息parameterType:指定包裝類型%${userCustom.username}%:userCustom是userQueryVo中的屬性,通過OGNL獲取屬性的值--><select id="findUserList" parameterType="userQueryVo" resultType="user">select id,username,birthday from user<!-- where標簽相當 于where關鍵字,可以自動去除第一個and --><where><!-- 引用sql片段,如果sql片段和引用處不在同一個mapper必須前邊加namespace --><include refid="query_user_where"></include><!-- 下邊還有很其它的條件 --><!-- <include refid="其它的sql片段"></include> --></where></select><!-- 使用resultMap作結果映射resultMap:如果引用resultMap的位置和resultMap的定義在同一個mapper.xml,直接使用resultMap的id,如果不在同一個mapper.xml要在resultMap的id前邊加namespace--><select id="findUserListResultMap" parameterType="userQueryVo" resultMap="userListResultMap">select id id_,username username_,birthday birthday_ from user where username like '%${userCustom.username}%'</select><!-- 輸出簡單類型功能:自定義查詢條件,返回查詢記錄個數,通常用于實現 查詢分頁--><select id="findUserCount" parameterType="userQueryVo" resultType="int">select count(*) from user <!-- where標簽相當 于where關鍵字,可以自動去除第一個and --><where><!-- 引用sql片段,如果sql片段和引用處不在同一個mapper必須前邊加namespace --><include refid="query_user_where"></include><!-- 下邊還有很其它的條件 --><!-- <include refid="其它的sql片段"></include> --></where></select><!-- 添加用戶parameterType:輸入 參數的類型,User對象 包括 username,birthday,sex,address#{}接收pojo數據,可以使用OGNL解析出pojo的屬性值#{username}表示從parameterType中獲取pojo的屬性值selectKey:用于進行主鍵返回,定義了獲取主鍵值的sqlorder:設置selectKey中sql執行的順序,相對于insert語句來說keyProperty:將主鍵值設置到哪個屬性resultType:select LAST_INSERT_ID()的結果 類型--><insert id="insertUser" parameterType="cn.learn.mybatis.po.User" ><selectKey keyProperty="id" order="AFTER" resultType="int">select LAST_INSERT_ID()</selectKey>INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})</insert><!-- mysql的uuid生成主鍵 --><!-- <insert id="insertUser" parameterType="cn.learn.mybatis.po.User"><selectKey keyProperty="id" order="BEFORE" resultType="string">select uuid()</selectKey>INSERT INTO USER(id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})</insert> --><!-- oracle在執行insert之前執行select 序列.nextval() from dual取出序列最大值,將值設置到user對象 的id屬性--><!-- <insert id="insertUser" parameterType="cn.learn.mybatis.po.User"><selectKey keyProperty="id" order="BEFORE" resultType="int">select 序列.nextval() from dual</selectKey>INSERT INTO USER(id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})</insert> --><!-- 用戶刪除 --><delete id="deleteUser" parameterType="int">delete from user where id=#{id}</delete><!-- 用戶更新 要求:傳入的user對象中包括 id屬性值--><update id="updateUser" parameterType="cn.learn.mybatis.po.User" flushCache="false">update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}</update></mapper>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"><!--diskStore:緩存數據持久化的目錄 地址 --><diskStore path="F:\develop\ehcache" /><defaultCache maxElementsInMemory="1000" maxElementsOnDisk="10000000"eternal="false" overflowToDisk="false" diskPersistent="true"timeToIdleSeconds="120"timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"></defaultCache>
</ehcache>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 屬性定義 加載一個properties文件 在 properties標簽 中配置屬性值 --><properties resource="db.properties"><!-- <property name="" value=""/> --></properties><!-- 全局配置參數 --><settings><!-- 延遲加載總開關 --><setting name="lazyLoadingEnabled" value="true" /> <!-- 設置按需加載 --><setting name="aggressiveLazyLoading" value="false" /><!-- 開啟二級緩存 --><setting name="cacheEnabled" value="true"/></settings><!-- 定義 別名 --><typeAliases><!-- 單個別名的定義 alias:別名,type:別名映射的類型 --><!-- <typeAlias type="cn.learn.mybatis.po.User" alias="user"/> --><!-- 批量別名定義 指定包路徑,自動掃描包下邊的pojo,定義別名,別名默認為類名(首字母小寫或大寫) --><package name="cn.learn.mybatis.po" /></typeAliases><!-- 和spring整合后 environments配置將廢除 --><environments default="development"><environment id="development"><!-- 使用jdbc事務管理 --><transactionManager type="JDBC" /><!-- 數據庫連接池 --><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></dataSource></environment></environments><!--加載mapper映射 如果將和spring整合后,可以使用整合包中提供的mapper掃描器,此處的mappers不用配置了。 --><mappers><!-- 通過resource引用mapper的映射文件 --><mapper resource="sqlmap/User.xml" /><!-- <mapper resource="mapper/UserMapper.xml" /> --><!-- 通過class引用mapper接口 class:配置mapper接口全限定名 要求:需要mapper.xml和mapper.java同名并且在一個目錄 中 --><!-- <mapper class="cn.learn.mybatis.mapper.UserMapper"/> --><!-- 批量mapper配置 通過package進行自動掃描包下邊的mapper接口, 要求:需要mapper.xml和mapper.java同名并且在一個目錄 中 --><package name="cn.learn.mybatis.mapper" /></mappers></configuration>
package cn.learn.mybatis.mapper;import java.io.IOException;
import java.io.InputStream;
import java.util.List;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import cn.learn.mybatis.po.OrderCustom;
import cn.learn.mybatis.po.Orders;
import cn.learn.mybatis.po.User;public class CacheTest {// 會話工廠private SqlSessionFactory sqlSessionFactory;// 創建工廠@Beforepublic void init() throws IOException {// 配置文件(SqlMapConfig.xml)String resource = "SqlMapConfig.xml";// 加載配置文件到輸入 流InputStream inputStream = Resources.getResourceAsStream(resource);// 創建會話工廠sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}//一級緩存@Testpublic void testCache1() throws Exception {SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//第一次查詢用戶id為1的用戶User user = userMapper.findUserById(1);System.out.println(user);//中間修改用戶要清空緩存,目的防止查詢出臟數據/*user.setUsername("測試用戶2");userMapper.updateUser(user);sqlSession.commit();*///第二次查詢用戶id為1的用戶User user2 = userMapper.findUserById(1);System.out.println(user2);sqlSession.close();}//二級緩存的測試@Testpublic void testCache2() throws Exception {SqlSession sqlSession1 = sqlSessionFactory.openSession();SqlSession sqlSession2 = sqlSessionFactory.openSession();SqlSession sqlSession3 = sqlSessionFactory.openSession();UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);//第一次查詢用戶id為1的用戶User user = userMapper1.findUserById(1);System.out.println(user);sqlSession1.close();//中間修改用戶要清空緩存,目的防止查詢出臟數據/*user.setUsername("測試用戶2");userMapper3.updateUser(user);sqlSession3.commit();sqlSession3.close();*///第二次查詢用戶id為1的用戶User user2 = userMapper2.findUserById(1);System.out.println(user2);sqlSession2.close();}}
/*** Copyright 2009-2015 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package org.apache.ibatis.cache;import java.util.concurrent.locks.ReadWriteLock;/*** SPI for cache providers.* * One instance of cache will be created for each namespace.* * The cache implementation must have a constructor that receives the cache id as an String parameter.* * MyBatis will pass the namespace as id to the constructor.* * <pre>* public MyCache(final String id) {* if (id == null) {* throw new IllegalArgumentException("Cache instances require an ID");* }* this.id = id;* initialize();* }* </pre>** @author Clinton Begin*/public interface Cache {/*** @return The identifier of this cache*/String getId();/*** @param key Can be any object but usually it is a {@link CacheKey}* @param value The result of a select.*/void putObject(Object key, Object value);/*** @param key The key* @return The object stored in the cache.*/Object getObject(Object key);/*** As of 3.3.0 this method is only called during a rollback * for any previous value that was missing in the cache.* This lets any blocking cache to release the lock that * may have previously put on the key.* A blocking cache puts a lock when a value is null * and releases it when the value is back again.* This way other threads will wait for the value to be * available instead of hitting the database.** * @param key The key* @return Not used*/Object removeObject(Object key);/*** Clears this cache instance*/ void clear();/*** Optional. This method is not called by the core.* * @return The number of elements stored in the cache (not its capacity).*/int getSize();/** * Optional. As of 3.2.6 this method is no longer called by the core.* * Any locking needed by the cache must be provided internally by the cache provider.* * @return A ReadWriteLock */ReadWriteLock getReadWriteLock();}
/*** Copyright 2009-2017 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package org.apache.ibatis.cache.impl;import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;/*** @author Clinton Begin*/
public class PerpetualCache implements Cache {private final String id;private Map<Object, Object> cache = new HashMap<Object, Object>();public PerpetualCache(String id) {this.id = id;}@Overridepublic String getId() {return id;}@Overridepublic int getSize() {return cache.size();}@Overridepublic void putObject(Object key, Object value) {cache.put(key, value);}@Overridepublic Object getObject(Object key) {return cache.get(key);}@Overridepublic Object removeObject(Object key) {return cache.remove(key);}@Overridepublic void clear() {cache.clear();}@Overridepublic ReadWriteLock getReadWriteLock() {return null;}@Overridepublic boolean equals(Object o) {if (getId() == null) {throw new CacheException("Cache instances require an ID.");}if (this == o) {return true;}if (!(o instanceof Cache)) {return false;}Cache otherCache = (Cache) o;return getId().equals(otherCache.getId());}@Overridepublic int hashCode() {if (getId() == null) {throw new CacheException("Cache instances require an ID.");}return getId().hashCode();}}
/** Copyright 2010 The MyBatis Team** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package org.mybatis.caches.ehcache;import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;/*** Cache adapter for Ehcache.** @version $Id: EhcacheCache.java 3454 2010-12-29 20:35:44Z simone.tripodi $*/
public final class EhcacheCache implements Cache {/*** The cache manager reference.*/private static final CacheManager CACHE_MANAGER = createCacheManager();/*** Looks for "/ehcache.xml" classpath resource and builds the relative* {@code CacheManager}; if it's no found or it is impossible to load it,* returns the default manager.** @return the application cache manager.*/private static CacheManager createCacheManager() {CacheManager cacheManager;InputStream input = EhcacheCache.class.getResourceAsStream("/ehcache.xml");if (input != null) {try {cacheManager = CacheManager.create(input);} catch (Throwable t) {cacheManager = CacheManager.create();} finally {try {input.close();} catch (IOException e) {}}} else {cacheManager = CacheManager.create();}return cacheManager;}/*** The {@code ReadWriteLock}.*/private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();/*** The cache id.*/private final String id;/***** @param id*/public EhcacheCache(final String id) {if (id == null) {throw new IllegalArgumentException("Cache instances require an ID");}this.id = id;if (!CACHE_MANAGER.cacheExists(this.id)) {CACHE_MANAGER.addCache(this.id);}}/*** {@inheritDoc}*/public void clear() {this.getCache().removeAll();}/*** {@inheritDoc}*/public String getId() {return this.id;}/*** {@inheritDoc}*/public Object getObject(Object key) {try {Element cachedElement = this.getCache().get(key.hashCode());if (cachedElement == null) {return null;}return cachedElement.getObjectValue();} catch (Throwable t) {throw new CacheException(t);}}/*** {@inheritDoc}*/public ReadWriteLock getReadWriteLock() {return this.readWriteLock;}/*** {@inheritDoc}*/public int getSize() {try {return this.getCache().getSize();} catch (Throwable t) {throw new CacheException(t);}}/*** {@inheritDoc}*/public void putObject(Object key, Object value) {try {this.getCache().put(new Element(key.hashCode(), value));} catch (Throwable t) {throw new CacheException(t);}}/*** {@inheritDoc}*/public Object removeObject(Object key) {try {Object obj = this.getObject(key);this.getCache().remove(key.hashCode());return obj;} catch (Throwable t) {throw new CacheException(t);}}/*** Returns the ehcache manager for this cache.** @return the ehcache manager for this cache.*/private Ehcache getCache() {return CACHE_MANAGER.getCache(this.id);}/*** {@inheritDoc}*/@Overridepublic boolean equals(Object obj) {if (this == obj) {return true;}if (obj == null) {return false;}if (!(obj instanceof Cache)) {return false;}Cache otherCache = (Cache) obj;return this.id.equals(otherCache.getId());}/*** {@inheritDoc}*/@Overridepublic int hashCode() {return this.id.hashCode();}/*** {@inheritDoc}*/@Overridepublic String toString() {return "EHCache {"+ this.id+ "}";}}
/** Copyright 2010 The MyBatis Team** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package org.mybatis.caches.ehcache;import org.apache.ibatis.cache.decorators.LoggingCache;/*** {@code LoggingCache} adapter for Ehcache.** @version $Id: LoggingEhcache.java 3454 2010-12-29 20:35:44Z simone.tripodi $*/
public final class LoggingEhcache extends LoggingCache {public LoggingEhcache(final String id) {super(new EhcacheCache(id));}}
?
總結
以上是生活随笔為你收集整理的mybatis和ehcache整合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决2次查询User的问题(Thread
- 下一篇: ThreadLocal类以及应用技巧