hibernate之二级缓存
1. 为什么需要缓存?
其实就是拉高程序的性能
2. 什么样的数据需要缓存?
很少被修改或根本不改的数据 数据字典业务场景比如:耗时较高的统计分析sql、电话账单查询sql等
3. ehcache是什么?
Ehcache 是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大注:本章介绍的是2.X版本,3.x的版本和2.x的版本API差异比较大
4. ehcache的特点
4.1 够快
Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.
4.2 够简单
开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用Ehcache,Ehcache被广泛的运用于其他的开源项目
4.3 够袖珍
关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2M,V 2.2.3 才 668KB。
4.4 够轻量
核心程序仅仅依赖slf4j这一个包,没有之一!
4.5 好扩展
Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多
4.6 监听器
缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener),做一些统计或数据一致性广播挺好用的
4.7 分布式缓存
从Ehcache 1.2开始,支持高性能的分布式缓存,兼具灵活性和扩展性
Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.
4.2 够简单
开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用Ehcache,Ehcache被广泛的运用于其他的开源项目
4.3 够袖珍
关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2M,V 2.2.3 才 668KB。
4.4 够轻量
核心程序仅仅依赖slf4j这一个包,没有之一!
4.5 好扩展
Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多
4.6 监听器
缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener),做一些统计或数据一致性广播挺好用的
4.7 分布式缓存
从Ehcache 1.2开始,支持高性能的分布式缓存,兼具灵活性和扩展性
5.实列
1、导入pom依赖
1 <project xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4 <modelVersion>4.0.0</modelVersion>
5 <groupId>com.yuan</groupId>
6 <artifactId>T226_hibernate</artifactId>
7 <packaging>war</packaging>
8 <version>0.0.1-SNAPSHOT</version>
9 <name>T226_hibernate Maven Webapp</name>
10 <url>http://maven.apache.org</url>
11 <properties>
12 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
13
14 <maven.compiler.source>1.8</maven.compiler.source>
15
16 <maven.compiler.target>1.8</maven.compiler.target>
17
18 <junit.version>4.12</junit.version>
19
20 <servlet.version>4.0.0</servlet.version>
21
22 <hibernate.version>5.2.12.Final</hibernate.version>
23
24 <mysql.driver.version>5.1.46</mysql.driver.version>
25
26 <ehcache.version>2.10.0</ehcache.version>
27
28 <slf4j-api.version>1.7.7</slf4j-api.version>
29
30 <log4j-api.version>2.9.1</log4j-api.version>
31 </properties>
32 <dependencies>
33
34
35 <dependency>
36
37 <groupId>junit</groupId>
38
39 <artifactId>junit</artifactId>
40
41 <version>${junit.version}</version>
42
43 <scope>test</scope>
44
45 </dependency>
46
47 <dependency>
48
49 <groupId>javax.servlet</groupId>
50
51 <artifactId>javax.servlet-api</artifactId>
52
53 <version>${servlet.version}</version>
54
55 <scope>provided</scope>
56
57 </dependency>
58
59
60 <dependency>
61
62 <groupId>org.hibernate</groupId>
63
64 <artifactId>hibernate-core</artifactId>
65
66 <version>${hibernate.version}</version>
67
68 </dependency>
69
70 <dependency>
71
72 <groupId>mysql</groupId>
73
74 <artifactId>mysql-connector-java</artifactId>
75
76 <version>${mysql.driver.version}</version>
77
78 </dependency>
79
80 <dependency>
81
82 <groupId>net.sf.ehcache</groupId>
83
84 <artifactId>ehcache</artifactId>
85
86 <version>${ehcache.version}</version>
87
88 </dependency>
89
90 <dependency>
91
92 <groupId>org.hibernate</groupId>
93
94 <artifactId>hibernate-ehcache</artifactId>
95
96 <version>${hibernate.version}</version>
97
98 </dependency>
99 <!-- slf4j核心包 -->
100
101 <dependency>
102
103 <groupId>org.slf4j</groupId>
104
105 <artifactId>slf4j-api</artifactId>
106
107 <version>${slf4j-api.version}</version>
108
109 </dependency>
110
111 <dependency>
112
113 <groupId>org.slf4j</groupId>
114
115 <artifactId>jcl-over-slf4j</artifactId>
116
117 <version>${slf4j-api.version}</version>
118
119 <scope>runtime</scope>
120
121 </dependency>
122
123 <!--用于与slf4j保持桥接 -->
124
125 <dependency>
126
127 <groupId>org.apache.logging.log4j</groupId>
128
129 <artifactId>log4j-slf4j-impl</artifactId>
130
131 <version>${log4j-api.version}</version>
132
133 </dependency>
134
135 <!--核心log4j2jar包 -->
136
137 <dependency>
138
139 <groupId>org.apache.logging.log4j</groupId>
140
141 <artifactId>log4j-api</artifactId>
142
143 <version>${log4j-api.version}</version>
144
145 </dependency>
146
147
148 <dependency>
149
150 <groupId>org.apache.logging.log4j</groupId>
151
152 <artifactId>log4j-core</artifactId>
153
154 <version>${log4j-api.version}</version>
155
156 </dependency>
157
158 </dependencies>
159 <build>
160 <finalName>T226_hibernate</finalName>
161 <plugins>
162 <plugin>
163 <groupId>org.apache.maven.plugins</groupId>
164 <artifactId>maven-compiler-plugin</artifactId>
165 <version>3.7.0</version>
166 <configuration>
167 <source>${maven.compiler.source}</source>
168 <target>${maven.compiler.target}</target>
169 <encoding>${project.build.sourceEncoding}</encoding>
170 </configuration>
171 </plugin>
172 </plugins>
173 </build>
174 </project>
2、工具类
1 package com.yuan.six.util;
2
3 import net.sf.ehcache.Cache;
4 import net.sf.ehcache.CacheManager;
5 import net.sf.ehcache.Element;
6
7 import java.io.InputStream;
8
9 public class EhcacheUtil {
10
11 private static CacheManager cacheManager;
12
13 static {
14 try {
15 InputStream is = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
16 cacheManager = CacheManager.create(is);
17 } catch (Exception e) {
18 throw new RuntimeException(e);
19 }
20 }
21
22 private EhcacheUtil() {
23 }
24
25 public static void put(String cacheName, Object key, Object value) {
26 Cache cache = cacheManager.getCache(cacheName);
27 if (null == cache) {
28 //以默认配置添加一个名叫cacheName的Cache
29 cacheManager.addCache(cacheName);
30 cache = cacheManager.getCache(cacheName);
31 }
32 cache.put(new Element(key, value));
33 }
34
35
36 public static Object get(String cacheName, Object key) {
37 Cache cache = cacheManager.getCache(cacheName);
38 Element element = cache.get(key);
39 return null == element ? null : element.getValue();
40 }
41
42 public static void remove(String cacheName, Object key) {
43 Cache cache = cacheManager.getCache(cacheName);
44 cache.remove(key);
45 }
46 }
SessionFactoryUtils
1 package com.yuan.two.util;
2
3 import org.hibernate.Session;
4 import org.hibernate.SessionFactory;
5 import org.hibernate.cfg.Configuration;
6
7
8 /**
9 * 仅在学习hibernate的工程中使用,当进入spring的学习后就没用了,后面会有ssh来替代它
10 * 作用:
11 * 用来检测hibernate中的配置文件的准确性,(hibernate.cfg.xml和*.hbm.xml)
12 *
13 *
14 * @author ly
15 *
16 */
17 public class SessionFactoryUtils {
18 private static SessionFactory sessionFactory;
19 static {
20 Configuration cfg = new Configuration().configure("/hibernate.cfg.xml");
21 sessionFactory = cfg.buildSessionFactory();
22 }
23
24 public static Session openSession() {
25 //从本地的线程中获取session会话,第一次肯定是获取不到的,那么需要重新让sessionfactory创建一个session出来
26 //第二次就能够对第一次创建的session反复利用,节约性能
27 Session session = sessionFactory.getCurrentSession();
28 if(session == null) {
29 session = sessionFactory.openSession();
30 }
31 return session;
32 }
33
34 public static void closeSession() {
35 Session session = sessionFactory.getCurrentSession();
36 if(session != null && session.isOpen()) {
37 session.close();
38 }
39 }
40
41 public static void main(String[] args) {
42 Session session = SessionFactoryUtils.openSession();
43 session.beginTransaction();
44 System.out.println(session.isConnected());
45 SessionFactoryUtils.closeSession();
46 System.out.println(session.isConnected());
47 }
48 }
3、导入我们外部调用的xml文件和配置
配置ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
<!--path:指定在硬盘上存储对象的路径-->
<!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
<diskStore path="D://xxx"/>
<!--defaultCache:默认的管理策略-->
<!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
<!--maxElementsInMemory:在内存中缓存的element的最大数目-->
<!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
<!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
<!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
<!--FIFO:first in first out (先进先出)-->
<!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
<!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="true" diskPersistent="false"
timeToIdleSeconds="600" timeToLiveSeconds="900" memoryStoreEvictionPolicy="LRU"/>
<!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
<cache name="com.yuan.one.entity.User" eternal="false" maxElementsInMemory="100"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
log4j2.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 <!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR
4 < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
5 <Configuration status="WARN" monitorInterval="30">
6 <Properties>
7 <!-- 配置日志文件输出目录 ${sys:user.home} -->
8 <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
9 <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
10 <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
11 <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
12 </Properties>
13
14 <Appenders>
15 <!--这个输出控制台的配置 -->
16 <Console name="Console" target="SYSTEM_OUT">
17 <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
18 <ThresholdFilter level="trace" onMatch="ACCEPT"
19 onMismatch="DENY" />
20 <!-- 输出日志的格式 -->
21 <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称
22 %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M
23 : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
24 <PatternLayout pattern="${PATTERN}" />
25 </Console>
26
27 <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
28 <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
29 <File name="log" fileName="logs/test.log" append="false">
30 <PatternLayout
31 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
32 </File>
33 <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
34 <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
35 filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
36 <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
37 <ThresholdFilter level="info" onMatch="ACCEPT"
38 onMismatch="DENY" />
39 <PatternLayout
40 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
41 <Policies>
42 <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
43 <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
44 <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
45 <TimeBasedTriggeringPolicy interval="1"
46 modulate="true" />
47 <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
48 <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
49 </Policies>
50 </RollingFile>
51
52 <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
53 filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
54 <ThresholdFilter level="warn" onMatch="ACCEPT"
55 onMismatch="DENY" />
56 <PatternLayout
57 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
58 <Policies>
59 <TimeBasedTriggeringPolicy />
60 <SizeBasedTriggeringPolicy size="2 kB" />
61 </Policies>
62 <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
63 <DefaultRolloverStrategy max="20" />
64 </RollingFile>
65
66 <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
67 filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
68 <ThresholdFilter level="error" onMatch="ACCEPT"
69 onMismatch="DENY" />
70 <PatternLayout
71 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
72 <Policies>
73 <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
74 <TimeBasedTriggeringPolicy interval="1"
75 modulate="true" />
76 <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
77 </Policies>
78 </RollingFile>
79
80 </Appenders>
81
82 <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
83 <Loggers>
84 <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
85 <logger name="org.springframework" level="INFO"></logger>
86 <logger name="org.mybatis" level="INFO"></logger>
87
88 <!-- 第三方日志系统 -->
89 <logger name="org.springframework" level="ERROR" />
90 <logger name="org.hibernate" level="ERROR" />
91 <logger name="org.apache.struts2" level="ERROR" />
92 <logger name="com.opensymphony.xwork2" level="ERROR" />
93 <logger name="org.jboss" level="ERROR" />
94
95
96 <!-- 配置日志的根节点 -->
97 <root level="all">
98 <appender-ref ref="Console" />
99 <appender-ref ref="RollingFileInfo" />
100 <appender-ref ref="RollingFileWarn" />
101 <appender-ref ref="RollingFileError" />
102 </root>
103
104 </Loggers>
105
106 </Configuration>
配置User.hbm.xml
在class中配置下面代码:
<cache usage="read-write" region="com.yuan.one.entity.User"/>
User.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-mapping PUBLIC
3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
5 <hibernate-mapping>
6 <!--
7 class标签中:
8 name:实体类的全路径
9 table:实体类对应数据库中的表
10 id标签:
11 name:实体类中的属性(映射的是表的主键)
12 type:属性对应的类型
13 Column:属性对应的表中的哪一个列段
14 property:
15 name:实体类中的属性(映射的是表的非主键字段)
16 type:属性对应的类型
17 Column:属性对应的表中的哪一个列段
18
19 List list = session.createQuery("from User").list();
20 1、建模hibernate.cfg.xml对象,从中拿到了com/yuan/one/entity/User.hbm.xml
21 2、建模了User.hbm.xml,拿到了com.yuan.one.entity.User 和 t_hibernate_User
22 3、User user = Class.forName("com.yuan.con.entity.User").newInstance();
23 Field userNameField = user.getClass("userName");
24 Field userPwdField = user.getClass("userPwd");
25 select user_name,user_pwd,real_name,.... 得到数据库对象信息
26 userNameField.set(user,源2);
27 userPwdField.set(user,mima)
28 ....
29 最后user中的所有属性值都有了
30 4、循环上一步操作,最终所有user实列都放入list集合中就是List list
31 -->
32 <class name="com.yuan.one.entity.User" table="t_hibernate_User">
33 <cache usage="read-write" region="com.yuan.one.entity.User"/>`
34 <id name="id" type="java.lang.Integer" column="id">
35 <generator class="increment" />
36 </id>
37 <property name="userName" type="java.lang.String" column="user_name">
38 </property>
39 <property name="userPwd" type="java.lang.String" column="user_pwd">
40 </property>
41 <property name="realName" type="java.lang.String" column="real_name">
42 </property>
43 <property name="sex" type="java.lang.String" column="sex">
44 </property>
45 <property name="birthday" type="java.sql.Date" column="birthday">
46 </property>
47 <property insert="false" update="false" name="createDatetime"
48 type="java.sql.Timestamp" column="create_datetime">
49 </property>
50 <property name="remark" type="java.lang.String" column="remark">
51 </property>
52 </class>
53
54 </hibernate-mapping>
配置hibernate.cfg.xml
代码:
1 <!-- 开启二级缓存 --> 2 <property name="hibernate.cache.use_second_level_cache">true</property> 3 <!-- 开启查询缓存 --> 4 <property name="hibernate.cache.use_query_cache">true</property> 5 <!-- EhCache驱动 --> 6 <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
hibernate.cfg.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <!-- 1. 数据库相关 --> 8 <property name="connection.username">root</property> 9 <property name="connection.password">123</property> 10 <property name="connection.url">jdbc:mysql://localhost:3306/xm_sc?useUnicode=true&characterEncoding=UTF-8 11 </property> 12 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 13 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 14 15 <!-- 配置本地事务(No CurrentSessionContext configured!) --> 16 <property name="hibernate.current_session_context_class">thread</property> 17 18 <!-- 2. 调试相关 --> 19 <property name="show_sql">true</property> 20 <property name="format_sql">true</property> 21 22 <!-- 开启二级缓存 --> 23 <property name="hibernate.cache.use_second_level_cache">true</property> 24 <!-- 开启查询缓存 --> 25 <property name="hibernate.cache.use_query_cache">true</property> 26 <!-- EhCache驱动 --> 27 <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> 28 29 30 <!-- 3. 添加实体映射文件 --> 31 <mapping resource="com/yuan/one/entity/User.hbm.xml" /> 32 <!-- 主键生成策略 --> 33 <mapping resource="com/yuan/two/Student.hbm.xml" /> 34 <mapping resource="com/yuan/two/Worker.hbm.xml" /> 35 <!-- 一对多关联关系 --> 36 <mapping resource="com/yuan/three/entity/Order.hbm.xml" /> 37 <mapping resource="com/yuan/three/entity/OrderItem.hbm.xml" /> 38 <!-- 一对多自关联关系 --> 39 <mapping resource="com/yuan/four/entity/TreeNode.hbm.xml" /> 40 <!-- 多对多关联关系 --> 41 <mapping resource="com/yuan/four/entity/book.hbm.xml" /> 42 <mapping resource="com/yuan/four/entity/category.hbm.xml" /> 43 </session-factory> 44 </hibernate-configuration>
6、测试类
EhcacheDemo1
1 package com.yuan.six.test;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 /**
7 * 利用map集合简易实现缓存原理
8 * @author Administrator
9 *
10 */
11 public class EhcacheDemo1 {
12 static Map<String, Object> cache = new HashMap<String, Object>();
13 static Object getValue(String key) {
14 Object value = cache.get(key);
15 System.out.println("从内存中读取数据");
16 if(value == null) {
17 System.out.println("从数据库中读取数据");
18 cache.put(key, new String[] {"zs"});
19 return cache.get(key);
20 }
21 return value;
22 }
23
24 public static void main(String[] args) {
25 System.out.println(getValue("sname"));
26 System.out.println(getValue("sname"));
27
28 //输出顺序:
29 // 第一次:
30 // 从内存中读取数据,第一次执行内存中没有东西
31 // 再到从数据库中读取数据,
32 // 返回zs并将值存入内存
33 // 第二次:
34 // 冲内存中读取数据,
35 // 直接返回zs
36 }
37 }
EhcacheDemo2
1 package com.yuan.six.test;
2
3 import com.yuan.six.util.EhcacheUtil;
4
5 /**
6 * 演示利用缓存存储数据
7 * @author Administrator
8 *
9 */
10 public class EhcacheDemo2 {
11 public static void main(String[] args) {
12 System.out.println(System.getProperty("java.io.tmpdir"));
13 EhcacheUtil.put("com.yuan.one.entity.User", 12, "lisi");
14 System.out.println(EhcacheUtil.get("com.yuan.one.entity.User", 12));
15 }
16 }
EhcacheDemo3
1 package com.yuan.six.test;
2
3 import org.hibernate.Session;
4 import org.hibernate.Transaction;
5
6 import com.yuan.one.entity.User;
7 import com.yuan.two.util.SessionFactoryUtils;
8
9
10 /**
11 * 演示查单个用户使用了缓存
12 * @author Administrator
13 *
14 */
15 public class EhcacheDemo3 {
16 /**
17 * 默认情况下,sql语句形成了三次,这里为了提高性能,必须使用二级缓存SessionFactory缓存
18 * <!-- 开启二级缓存 -->
19 * <property name="hibernate.cache.use_second_level_cache">true</property>
20 <!-- 开启查询缓存 -->
21 <property name="hibernate.cache.use_query_cache">true</property>
22 <!-- EhCache驱动 -->
23 <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
24
25 映射文件中添加标签
26 <cache usage="read-write" region="com.javaxl.one.entity.User"/>
27 这里的region指的是Ehcache.xml中cacheName
28 * @param args
29 */
30 public static void main(String[] args) {
31 // UserDao userDao = new UserDao();
32 // User u = new User();
33 // u.setId(7);
34 // User user = userDao.get(u);
35 // System.out.println(user);
36 // User user2 = userDao.get(u);
37 // System.out.println(user2);
38 // User user3 = userDao.get(u);
39 // System.out.println(user3);
40
41 }
42
43 /**
44 * 同一个session,sql语句只生成一次,这里用到了一级缓存
45 */
46 public static void test1() {
47 Session session = SessionFactoryUtils.openSession();
48 Transaction transaction = session.beginTransaction();
49
50 User user = session.get(User.class, 7);
51 System.out.println(user);
52 User user2 = session.get(User.class, 7);
53 System.out.println(user2);
54 User user3 = session.get(User.class, 7);
55 System.out.println(user3);
56
57 transaction.commit();
58 session.close();
59 }
60 }
EhcacheDemo4
1 package com.yuan.six.test;
2
3 import java.util.List;
4
5 import org.hibernate.Session;
6 import org.hibernate.Transaction;
7 import org.hibernate.query.Query;
8
9 import com.yuan.two.util.SessionFactoryUtils;
10
11
12 /**
13 * hibernate二级缓存不会同时缓存多条数据
14 * @author Administrator
15 *
16 */
17 public class EhcacheDemo4 {
18 public static void main(String[] args) {
19 Session session = SessionFactoryUtils.openSession();
20 Transaction transaction = session.beginTransaction();
21
22 Query query = session.createQuery("from User");
23 query.setCacheable(true);
24 List list = query.list();
25 System.out.println(list);
26 List list2 = query.list();
27 System.out.println(list2);
28 List list3 = query.list();
29 System.out.println(list3);
30
31
32 transaction.commit();
33 session.close();
34 }
35 }
谢谢观看 !!!