hibernate<8>----二级缓存
User.java
package cn.anycall.hibernate.domain;import java.util.Date;public class User {private int id;private String name;private Date birthday;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.anycall.hibernate.domain"><class name="User" table="user"><cache usage="read-write"/><id name="id" column="id"><generator name="code"><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql:///test</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">123456</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><property name="hbm2ddl.auto">create</property><property name="show_sql">true</property><property name="cache.use_second_level_cache">true</property><property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property><property name="hibernate.generate_statistics">true</property><property name="cache.use_query_cache">true</property><!-- <class-cache usage="read-write"/> --><mapping resource="cn/anycall/hibernate/domain/User.hbm.xml"/></session-factory></hibernate-configuration>
# CACHE IN MEMORY## If you want to disable memory caching, just uncomment this line.## cache.memory=false# CACHE KEY## This is the key that will be used to store the cache in the application# and session scope.## If you want to set the cache key to anything other than the default# uncomment this line and change the cache.key## cache.key=__oscache_cache# USE HOST DOMAIN NAME IN KEY## Servers for multiple host domains may wish to add host name info to# the generation of the key. If this is true, then uncomment the# following line.## cache.use.host.domain.in.key=true# CACHE LISTENERS## These hook OSCache events and perform various actions such as logging# cache hits and misses, or broadcasting to other cache instances across a cluster.# See the documentation for further information.## cache.event.listeners=com.opensymphony.oscache.plugins.clustersupport.JMSBroadcastingListener, \# com.opensymphony.oscache.extra.CacheEntryEventListenerImpl, \# com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl, \# com.opensymphony.oscache.extra.ScopeEventListenerImpl# CACHE PERSISTENCE CLASS## Specify the class to use for persistence. If you use the supplied DiskPersistenceListener,# don't forget to supply the cache.path property to specify the location of the cache# directory.# # If a persistence class is not specified, OSCache will use memory caching only.## cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener# CACHE DIRECTORY## This is the directory on disk where caches will be stored by the DiskPersistenceListener.# it will be created if it doesn't already exist. Remember that OSCache must have# write permission to this directory.## Note: for Windows machines, this needs \ to be escaped# ie Windows:# cache.path=c:\\myapp\\cache# or *ix:# cache.path=/opt/myapp/cache## cache.path=c:\\app\\cache# CACHE ALGORITHM## Default cache algorithm to use. Note that in order to use an algorithm# the cache size must also be specified. If the cache size is not specified,# the cache algorithm will be Unlimited cache.## cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache# cache.algorithm=com.opensymphony.oscache.base.algorithm.FIFOCache# cache.algorithm=com.opensymphony.oscache.base.algorithm.UnlimitedCache# CACHE SIZE## Default cache size in number of items. If a size is specified but not# an algorithm, the cache algorithm used will be LRUCache.#cache.capacity=100000# CACHE UNLIMITED DISK# Use unlimited disk cache or not. The default value is false, which means# the disk cache will be limited in size to the value specified by cache.capacity.## cache.unlimited.disk=false# JMS CLUSTER PROPERTIES## Configuration properties for JMS clustering. See the clustering documentation# for more information on these settings.##cache.cluster.jms.topic.factory=java:comp/env/jms/TopicConnectionFactory#cache.cluster.jms.topic.name=java:comp/env/jms/OSCacheTopic#cache.cluster.jms.node.name=node1# JAVAGROUPS CLUSTER PROPERTIES## Configuration properites for the JavaGroups clustering. Only one of these# should be specified. Default values (as shown below) will be used if niether# property is set. See the clustering documentation and the JavaGroups project# (www.javagroups.com) for more information on these settings.##cache.cluster.properties=UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;mcast_send_buf_size=150000;mcast_recv_buf_size=80000):PING(timeout=2000;num_initial_members=3):MERGE2(min_interval=5000;max_interval=10000):FD_SOCK:VERIFY_SUSPECT(timeout=1500):pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800):pbcast.STABLE(desired_avg_gossip=20000):UNICAST(timeout=5000):FRAG(frag_size=8096;down_thread=false;up_thread=false):pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=true)#cache.cluster.multicast.ip=231.12.21.132
package cn.anycall.hibernate;import java.io.Serializable;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public final class HibernateUtil {private static SessionFactory sessionFactory;public static SessionFactory getSessionFactory() {return sessionFactory;}public static void setSessionFactory(SessionFactory sessionFactory) {HibernateUtil.sessionFactory = sessionFactory;}private HibernateUtil(){}public static Session getSession(){return getSessionFactory().openSession();}static{Configuration cfg = new Configuration();cfg.configure();sessionFactory = cfg.buildSessionFactory();}public static void add(Object entity){Session s = null;Transaction tx = null;try{s = HibernateUtil.getSession();tx = s.beginTransaction();s.save(entity);tx.commit();}finally{if(s !=null)s.close();}}public static void update(Object entity){Session s = null;Transaction tx = null;try{s = HibernateUtil.getSession();tx = s.beginTransaction();s.update(entity);tx.commit();}finally{if(s !=null)s.close();}}public static void delete(Object entity){Session s = null;Transaction tx = null;try{s = HibernateUtil.getSession();tx = s.beginTransaction();s.delete(entity);tx.commit();}finally{if(s !=null)s.close();}}public static Object get(Class clazz, Serializable id){Session s = null;try{s = HibernateUtil.getSession();Object obj = s.get(clazz, id);return obj;}finally{if(s !=null)s.close();}}}package cn.anycall.hibernate;import java.util.Date;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.stat.Statistics;import cn.anycall.hibernate.domain.User;public class CatchTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubUser user = addUser();getUser(user.getId());Statistics st = HibernateUtil.getSessionFactory().getStatistics();System.out.println("put:"+st.getSecondLevelCachePutCount());System.out.println("hit:"+st.getSecondLevelCacheHitCount());System.out.println("miss:"+st.getSecondLevelCacheMissCount());}static User getUser(int id){Session s = null;User user = null;try{s = HibernateUtil.getSession(); user = (User)s.get(User.class, id);// s.evict(user); s.clear();System.out.println(user.getName());user = (User)s.get(User.class, id);}finally{if(s!=null)s.close();}try{s = HibernateUtil.getSession(); user = (User)s.get(User.class, id);// s.evict(user);System.out.println(user.getName()); s.clear();user = (User)s.get(User.class, id);}finally{if(s!=null)s.close();}try{s = HibernateUtil.getSession(); user = (User)s.get(User.class, id);// s.evict(user);System.out.println(user.getName()); s.clear();user = (User)s.get(User.class, id);}finally{if(s!=null)s.close();}try{s = HibernateUtil.getSession();Query q = s.createQuery("from User");q.setCacheable(true);user = (User)q.uniqueResult();System.out.println(user.getName());}finally{if(s!=null)s.close();}return user;}static User addUser(){User user = new User();user.setBirthday(new Date());user.setName("user");HibernateUtil.add(user);return user;}}