新建test项目→新建实体类Person→加入jar包
Person实体类代码:
@Entity
@Table(name = "person")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Person implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String age;
...略去get/set
}
Person.hbm.xml代码:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.test.cache">
<class name="Person" table="person">
<cache usage="read-write" />
<id name="id" type="int">
<generator class="increment" />
</id>
<property name="name" column="name" type="string"
not-null="false" length="36" />
<property name="age" column="age" type="string"
length="100" />
</class>
</hibernate-mapping>
操作步骤如下:::
第一步:加入到类路径下hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
org.gjt.mm.mysql.Driver
</property>
<property name="connection.url">
jdbc:mysql://192.168.1.120:3306/test?useUnicode=true&characterEncoding=utf-8
</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.pool_size">10</property>
<property name="hibernate.jdbc.batch_size">10</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="hbm2ddl.auto">none</property>
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
<!-- Enable Second-Level Cache and Query Cache Settings -->
<property name="hibernate.cache.use_second_level_cache">
true
</property>
<property name="hibernate.cache.use_query_cache">
false
</property>
<!-- 注解配置 -->
<mapping class="com.test.cache.Person" />
<!-- 映射文件 -->
<mapping
resource="com/test/cache/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
第二步:测试一级缓存与二级缓存/查询缓存
1.测试一级缓存代码(get()方法/load()方法+second_level_cache=false,query_cache=false):
/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
SessionFactory sessionFactory = null;
try {
System.out.println("ehcache - hibernate Test ...");
Configuration config = new AnnotationConfiguration()
.configure("hibernate.cfg.xml");
sessionFactory = config.buildSessionFactory();
System.out.println("在同一个session中执行:::");
Session session = sessionFactory.getCurrentSession();
Transaction ta = session.beginTransaction();
Person person = (Person) session.get(Person.class, 1);
System.out.println(person.getName());
System.out.println("第二次查询开始。。。。。");
Person pern = (Person) session.get(Person.class, 1);
ta.commit();
System.out.println(pern.getName());
}
执行结果为:
ehcache - hibernate Test ...
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
在同一个session中执行:::
Hibernate:
select
person0_.id as id0_0_,
person0_.name as name0_0_,
person0_.age as age0_0_
from
person person0_
where
person0_.id=?
yf
第二次查询开始。。。。。
yf
sessionFactory closed.
可以看出第二次执行未执行sql
2.测试2级级缓存代码(get()方法/load方法+second_level_cache=true,query_cache=false):
/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
SessionFactory sessionFactory = null;
try {
System.out.println("ehcache - hibernate Test ...");
Configuration config = new AnnotationConfiguration()
.configure("hibernate.cfg.xml");
sessionFactory = config.buildSessionFactory();
System.out.println("不在同一个session中执行======");
Session session = sessionFactory.openSession();
Transaction ta = session.beginTransaction();
Person person = (Person) session.get(Person.class, 1);
ta.commit();
System.out.println(person.getName());
System.out.println("第二次查询开始。。。。。");
Session sess = sessionFactory.openSession();
Transaction trans = session.beginTransaction();
Person pern = (Person) sess.get(Person.class, 1);
trans.commit();
System.out.println(pern.getName());
}
执行结果为:
ehcache - hibernate Test ...
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
不在同一个session中执行======
Hibernate:
select
person0_.id as id0_0_,
person0_.name as name0_0_,
person0_.age as age0_0_
from
person person0_
where
person0_.id=?
yf
第二次查询开始。。。。。
yf
sessionFactory closed.
可以看出第二次执行未执行sql
3.测试2级查询缓存(list()方法)+second_level=true,query_cache=false):
这种方式,query查询会缓存查询结果数据到2级缓存里,但是不会执行查询缓存
4.测试2级查询缓存(list()方法)+second_level=true,query_cache=true):
System.out.println("不在同一个session中执行list()======");
Session session = sessionFactory.openSession();
Transaction ta = session.beginTransaction();
String hql = "select t from Person t where t.name='ryan'";
Query que = session.createQuery(hql);
que.setCacheable(true);
System.out.println("list().size==" + que.list().size());
ta.commit();
System.out.println("第二次查询开始。。。。。");
Session sess = sessionFactory.openSession();
Transaction trans = session.beginTransaction();
String shql = "select t from Person t where t.name='ryan'";
Query query = sess.createQuery(shql);
query.setCacheable(true);
System.out.println("list().size==" + query.list().size());
trans.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != sessionFactory) {
sessionFactory.close();
}
}
System.out.println("sessionFactory closed.");
}
执行结果:第二次查询并没有访问数据库,查询缓存使用hibernate生成的sql和参数生成缓存的key,再执行相同sql和相同条件的时候直接从缓存中去。
INFO org.hibernate.cache.UpdateTimestampsCache - starting update timestamps cache at region: org.hibernate.cache.UpdateTimestampsCache
INFO org.hibernate.cache.StandardQueryCache - starting query cache at region: org.hibernate.cache.StandardQueryCache
不在同一个session中执行list()======
Hibernate:
select
person0_.id as id0_,
person0_.name as name0_,
person0_.age as age0_
from
person person0_
where
person0_.name='ryan'
list().size==2
第二次查询开始。。。。。
list().size==2
INFO org.hibernate.impl.SessionFactoryImpl - closing
INFO org.hibernate.connection.DriverManagerConnectionProvider - cleaning up connection pool: jdbc:mysql://192.168.1.120:3306/test?useUnicode=true&characterEncoding=utf-8
sessionFactory closed.