大家好,又见面了,我是你们的朋友全栈君。
hibernate默认有一个一级缓存,就是默认的Session缓存,当我们做了一次查询,hibernate会把这个结果缓存起来,叫做一级缓存,当我们接着在这个Session会话里面再做一次同样条件的查询,hibernate不会再次查询数据库,而是直接在一级缓存中获取结果并返回。一级缓存是内置的,他也不能被卸载。一级缓存是指在同一个Session会话内的查询做的缓存,如果跨了Session,或者当前Session关闭,重新开启了一个新的Session,这时候一级缓存是失效的。
二级缓存是一个可插拔的缓存,可有可无,如果你配置了,他就有,没有配置就没有。二级缓存的实现,默认是用ehcache,需要增加一个配置文件ehcache.xml,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
</ehcache>
实体类如下:
BaseEntity.java
package com.xxx.hibernate.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
protected Integer id;
@Column(name="modifydate")
protected Date modifyDate;
@Column(name="createdate")
protected Date createDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
User.java
package com.xxx.hibernate.domain;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Table(name="xx_user")
@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User extends BaseEntity{
private String name;
private int age;
private String email;
private String mobile;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "user:[id="+id+",name="+name+",age="+age+
",email="+email+",mobile="+mobile+"]";
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=utf-8&useSSL=false</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">20</property>
<property name="dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_query_cache">true</property>
<mapping class="com.xxx.hibernate.domain.User"/>
</session-factory>
</hibernate-configuration>
测试类代码:
package com.xxx.hibernate.test;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.xxx.hibernate.domain.User;
public class HibernateAppTest {
private static SessionFactory sessionFactory;
private static final ThreadLocal<Session> session = new ThreadLocal<Session>();
static{
try {
Configuration cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Session getSession(){
Session sess = session.get();
if(sess==null){
sess = sessionFactory.openSession();
session.set(sess);
}
return sess;
}
public static void closeSession(){
Session sess = session.get();
if(sess!=null){
sess.close();
}
session.set(null);
sessionFactory.close();
}
public static void add(String name,int age,String email,String mobile,String password){
User user = new User();
user.setName(name);
user.setAge(age);
user.setEmail(email);
user.setMobile(mobile);
user.setPassword(password);
user.setCreateDate(new Date());
user.setModifyDate(new Date());
//
Session sess = getSession();
Transaction tx = sess.beginTransaction();
sess.save(user);
tx.commit();
closeSession();
}
public static void search(Integer id){
Session sess = getSession();
User user = sess.get(User.class, id);
if(user!=null)
System.out.println(user);
}
public static void testDefaultCache(){
long start = System.currentTimeMillis();
search(2);
long end = System.currentTimeMillis();
System.out.println("it takes "+(end-start)+" .");
//======================
start = System.currentTimeMillis();
search(2);
end = System.currentTimeMillis();
System.out.println("it takes "+(end-start)+" .");
start = System.currentTimeMillis();
search(1);
end = System.currentTimeMillis();
System.out.println("it takes "+(end-start)+" .");
closeSession();
}
@SuppressWarnings("unchecked")
public static void testL2Cache(){
Session sess = sessionFactory.openSession();
List<User> list = sess.createQuery("from User").setCacheable(true).list();
for(User user:list){
System.out.println(user);
}
sess.close();
System.out.println("=======================分割线======================");
Session sess2 = sessionFactory.openSession();
list = sess2.createQuery("from User").setCacheable(true).list();
for(User user:list){
System.out.println(user);
}
sess2.close();
closeSession();
}
public static void main(String[] args) {
//add("xxx", 18, "xxx@hibernate.cn", "15902020509", "123456");
//add("aaa", 33, "aaa@hibernate.cn", "15902020520", "123456");
//testDefaultCache();
testL2Cache();
}
}
运行testL2Cache()方法,打印关键信息如下:
第一次查询,打印了sql语句,说明从数据库中做了查询,第二次查询,直接使用了二级缓存,因此,并没有打印sql语句。这个结果说明hibernate二级缓存配置正确并且生效了。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/142508.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...