MyBatis_cache
Teacher.java:
1 package com.atguigu.bean; 2 3 import java.io.Serializable; 4 import java.util.Date; 5 6 public class Teacher{ 7 8 private Integer id; 9 private String name; 10 private String course; 11 private String address; 12 private Date birth; 13 /** 14 * @return the id 15 */ 16 public Integer getId() { 17 return id; 18 } 19 /** 20 * @param id the id to set 21 */ 22 public void setId(Integer id) { 23 this.id = id; 24 } 25 /** 26 * @return the name 27 */ 28 public String getName() { 29 return name; 30 } 31 /** 32 * @param name the name to set 33 */ 34 public void setName(String name) { 35 this.name = name; 36 } 37 /** 38 * @return the course 39 */ 40 public String getCourse() { 41 return course; 42 } 43 /** 44 * @param course the course to set 45 */ 46 public void setCourse(String course) { 47 this.course = course; 48 } 49 /** 50 * @return the address 51 */ 52 public String getAddress() { 53 return address; 54 } 55 /** 56 * @param address the address to set 57 */ 58 public void setAddress(String address) { 59 this.address = address; 60 } 61 /** 62 * @return the birth 63 */ 64 public Date getBirth() { 65 return birth; 66 } 67 /** 68 * @param birth the birth to set 69 */ 70 public void setBirth(Date birth) { 71 this.birth = birth; 72 } 73 /* (non-Javadoc) 74 * @see java.lang.Object#toString() 75 */ 76 @Override 77 public String toString() { 78 return "Teacher [id=" + id + ", name=" + name + ", course=" + course 79 + ", address=" + address + ", birth=" + birth + "]"; 80 } 81 82 }
MyCache.java:
1 package com.atguigu.dao; 2 3 import java.util.concurrent.locks.ReadWriteLock; 4 5 import org.apache.ibatis.cache.Cache; 6 7 public class MyCache implements Cache { 8 //redis = new Redis(); 9 10 @Override 11 public String getId() { 12 // TODO Auto-generated method stub 13 return null; 14 } 15 16 @Override 17 public void putObject(Object key, Object value) { 18 // TODO Auto-generated method stub 19 // mybatis-ehcache-1.0.3.jar ehcache-core-2.6.8.jar 20 /** 21 * 22 */ 23 //redis.put(); 24 } 25 26 @Override 27 public Object getObject(Object key) { 28 // TODO Auto-generated method stub 29 //redis.get 30 return null; 31 } 32 33 @Override 34 public Object removeObject(Object key) { 35 // TODO Auto-generated method stub 36 return null; 37 } 38 39 @Override 40 public void clear() { 41 // TODO Auto-generated method stub 42 43 } 44 45 @Override 46 public int getSize() { 47 // TODO Auto-generated method stub 48 return 0; 49 } 50 51 @Override 52 public ReadWriteLock getReadWriteLock() { 53 // TODO Auto-generated method stub 54 return null; 55 } 56 57 }
TeacherDao.java:
1 package com.atguigu.dao; 2 3 import java.util.List; 4 5 import org.apache.ibatis.annotations.Param; 6 7 import com.atguigu.bean.Teacher; 8 9 public interface TeacherDao { 10 11 public Teacher getTeacherById(Integer id); 12 13 public List<Teacher> getTeacherByCondition(Teacher teacher); 14 15 public List<Teacher> getTeacherByIdIn(@Param("ids")List<Integer> ids); 16 17 public List<Teacher> getTeacherByConditionChoose(Teacher teacher); 18 19 public int updateTeacher(Teacher teacher); 20 21 }
EmployeeDao.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="com.atguigu.dao.EmployeeDao"> 6 7 <!--和别的dao公用一块缓存--> 8 <cache-ref namespace="com.atguigu.dao.TeacherDao"/> 9 </mapper>
TeacherDao.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="com.atguigu.dao.TeacherDao"> 6 <!-- 使用mybatis默认二级缓存<cache></cache> --> 7 <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache> 8 9 <resultMap type="com.atguigu.bean.Teacher" id="teacherMap"> 10 <id property="id" column="id" /> 11 <result property="address" column="address" /> 12 <result property="birth" column="birth_date" /> 13 <result property="course" column="class_name" /> 14 <result property="name" column="teacherName" /> 15 </resultMap> 16 17 <!--抽取可重用的sql语句 --> 18 <sql id="selectSql">select * from t_teacher</sql> 19 <!--public Teacher getTeacherById(Integer id); --> 20 <!-- 是否使用二级缓存的useCache="true";默认是true --> 21 <select id="getTeacherById" resultMap="teacherMap"> 22 <include refid="selectSql"></include> 23 where id=#{id} 24 </select> 25 26 <!-- if:判断 --> 27 <!--public List<Teacher> getTeacherByCondition(Teacher teacher); --> 28 <select id="getTeacherByCondition" resultMap="teacherMap"> 29 select * from t_teacher 30 <!-- test="":编写判断条件 id!=null:取出传入的javaBean属性中的id的值,判断其是否为空 --> 31 <!-- where可以帮我们去除掉前面的and; --> 32 33 <!-- trim:截取字符串 34 prefix="":前缀;为我们下面的sql整体添加一个前缀 35 prefixOverrides="": 取出整体字符串前面多余的字符 36 suffix="":为整体添加一个后缀 37 suffixOverrides="":后面哪个多了可以去掉; --> 38 <!-- 我们的查询条件就放在where标签中;每个and写在前面, 39 where帮我们自动取出前面多余的and --> 40 <trim prefix="where" prefixOverrides="and" suffixOverrides="and"> 41 <if test="id!=null"> 42 id > #{id} and 43 </if> 44 <!-- 空串 "" and; && or: ||; if():传入非常强大的判断条件; 45 OGNL表达式;对象导航图 46 Person 47 ===lastName 48 ===email 49 ===Address 50 ===city 51 ===province 52 ===Street 53 ===adminName 54 ===info 55 ===perCount 56 方法、静态方法、构造器。xxx 57 在mybatis中,传入的参数可以用来做判断; 58 额外还有两个东西; 59 _parameter:代表传入来的参数; 60 1)、传入了单个参数:_parameter就代表这个参数 61 2)、传入了多个参数:_parameter就代表多个参数集合起来的map 62 _databaseId:代表当前环境 63 如果配置了databaseIdProvider:_databaseId就有值 64 65 --> 66 <!-- 绑定一个表达式的值到一个变量 --> 67 <!-- <bind name="_name" value="'%'+name+'%'"/> --> 68 <if test="name!=null && !name.equals("")"> 69 teacherName like #{_name} and 70 </if> 71 <if test="birth!=null"> 72 birth_date < #{birth} and 73 </if> 74 </trim> 75 </select> 76 77 <!-- public List<Teacher> getTeacherByIdIn(List<Integer> ids); --> 78 <select id="getTeacherByIdIn" resultMap="teacherMap"> 79 80 SELECT * FROM t_teacher WHERE id IN 81 <!-- 帮我们遍历集合的; collection="":指定要遍历的集合的key 82 close="":以什么结束 83 index="i":索引; 84 如果遍历的是一个list; 85 index:指定的变量保存了当前索引 86 item:保存当前遍历的元素的值 87 如果遍历的是一个map: 88 index:指定的变量就是保存了当前遍历的元素的key 89 item:就是保存当前遍历的元素的值 90 item="变量名":每次遍历出的元素起一个变量名方便引用 91 open="":以什么开始 92 separator="":每次遍历的元素的分隔符 93 (#{id_item},#{id_item},#{id_item} --> 94 <if test="ids.size >0"> 95 <foreach collection="ids" item="id_item" separator="," open="(" 96 close=")"> 97 #{id_item} 98 </foreach> 99 </if> 100 </select> 101 102 <!--public List<Teacher> getTeacherByConditionChoose(Teacher teacher); --> 103 <select id="getTeacherByConditionChoose" resultMap="teacherMap"> 104 select * from t_teacher 105 <where> 106 <choose> 107 <when test="id!=null"> 108 id=#{id} 109 </when> 110 <when test="name!=null and !name.equals("")"> 111 teacherName=#{name} 112 </when> 113 <when test="birth!=null"> 114 birth_date = #{birth} 115 </when> 116 <otherwise> 117 1=1 118 </otherwise> 119 </choose> 120 </where> 121 </select> 122 123 <!-- public int updateTeacher(Teacher teacher); --> 124 <update id="updateTeacher" > 125 UPDATE t_teacher 126 <set> 127 <if test="name!=null and !name.equals("")"> 128 teacherName=#{name}, 129 </if> 130 <if test="course!=null and !course.equals("")"> 131 class_name=#{course}, 132 </if> 133 <if test="address!=null and !address.equals("")"> 134 address=#{address}, 135 </if> 136 <if test="birth!=null"> 137 birth_date=#{birth} 138 </if> 139 </set> 140 <where> 141 id=#{id} 142 </where> 143 144 </update> 145 </mapper>
ehcache.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> 4 <!-- 磁盘保存路径 --> 5 <diskStore path="D:44ehcache" /> 6 <defaultCache 7 maxElementsInMemory="1" 8 maxElementsOnDisk="10000000" 9 eternal="false" 10 overflowToDisk="true" 11 timeToIdleSeconds="120" 12 timeToLiveSeconds="120" 13 diskExpiryThreadIntervalSeconds="120" 14 memoryStoreEvictionPolicy="LRU"> 15 </defaultCache> 16 </ehcache> 17 18 <!-- 19 属性说明: 20 l diskStore:指定数据在磁盘中的存储位置。 21 l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略 22 23 以下属性是必须的: 24 l maxElementsInMemory - 在内存中缓存的element的最大数目 25 l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大 26 l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断 27 l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上 28 29 以下属性是可选的: 30 l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大 31 l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大 32 diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区. 33 l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。 34 l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作 35 l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出) 36 -->
log4j.xml:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> 3 4 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> 5 6 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> 7 <param name="Encoding" value="UTF-8" /> 8 <layout class="org.apache.log4j.PatternLayout"> 9 <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) " /> 10 </layout> 11 </appender> 12 <logger name="java.sql"> 13 <level value="debug" /> 14 </logger> 15 <logger name="org.apache.ibatis"> 16 <level value="info" /> 17 </logger> 18 <root> 19 <level value="debug" /> 20 <appender-ref ref="STDOUT" /> 21 </root> 22 </log4j:configuration>
mybatis-config.xml:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 7 <settings> 8 <!-- 开启延迟加载开关 --> 9 <setting name="lazyLoadingEnabled" value="true"/> 10 <!-- 开启属性按需加载 --> 11 <setting name="aggressiveLazyLoading" value="false"/> 12 <!-- 开启全局缓存开关;需要在dao.xml文件中指定 --> 13 <setting name="cacheEnabled" value="true"/> 14 </settings> 15 <environments default="development"> 16 <environment id="development"> 17 <transactionManager type="JDBC" /> 18 <dataSource type="POOLED"> 19 <property name="driver" value="com.mysql.cj.jdbc.Driver" /> 20 <property name="url" value="jdbc:mysql://localhost:3306/mybatis_0325?characterEncoding=utf-8&serverTimezone=GMT%2B8" /> 21 <property name="username" value="root" /> 22 <property name="password" value="root" /> 23 </dataSource> 24 </environment> 25 </environments> 26 27 <mappers> 28 <package name="com.atguigu.dao"/> 29 </mappers> 30 </configuration>
pom.xml:
1 <dependencies> 2 <dependency> 3 <groupId>junit</groupId> 4 <artifactId>junit</artifactId> 5 <version>4.8.2</version> 6 <scope>compile</scope> 7 </dependency> 8 9 <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core --> 10 <dependency> 11 <groupId>net.sf.ehcache</groupId> 12 <artifactId>ehcache-core</artifactId> 13 <version>2.6.11</version> 14 </dependency> 15 16 <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> 17 <dependency> 18 <groupId>org.slf4j</groupId> 19 <artifactId>slf4j-log4j12</artifactId> 20 <version>1.7.30</version> 21 <scope>test</scope> 22 </dependency> 23 24 <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --> 25 <dependency> 26 <groupId>org.slf4j</groupId> 27 <artifactId>slf4j-api</artifactId> 28 <version>1.7.30</version> 29 </dependency> 30 31 <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache --> 32 <dependency> 33 <groupId>org.mybatis.caches</groupId> 34 <artifactId>mybatis-ehcache</artifactId> 35 <version>1.2.1</version> 36 </dependency> 37 38 </dependencies>