mysql一级缓存二级缓存案例_hibernate(六)之一级缓存、二级缓存案例

1.要实现二级缓存,需另加以下jar包:

ehcache-core-2.4.3.jar、hibernate-core-4.2.3.Final.jar、slf4j-api-1.6.6.jar

2.需要更改配置文件

hibernate.cfg.xml

/p>

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

com.mysql.jdbc.Driver

jdbc:mysql://127.0.0.1:3306/hibernate_db

root

beanGou

1

org.hibernate.dialect.MySQLDialect

thread

org.hibernate.cache.ehcache.EhCacheRegionFactory

ehcache2.xml

true

true

true

update

如果要给某个类设置二级缓存,则相应的改其配置文件,如

Employee.hbm.xml

/p>

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

3.测试代码

@Test

public void get() {

Session session = HibernateUtil.getSession();

Employee employee = (Employee) session.get(Employee.class, 1);

employee = (Employee) session.get(Employee.class, 1);

System.out.println(employee.getName());

session.evict(employee);

employee = (Employee) session.get(Employee.class, 1);

session.close();

Statistics statistics = HibernateUtil.getSessionFactory().getStatistics();

System.out.println(statistics);

System.out.println("命中数:" + statistics.getSecondLevelCacheHitCount());

System.out.println("错过数:" + statistics.getSecondLevelCacheMissCount());

System.out.println("放入数:" + statistics.getSecondLevelCachePutCount());

}

注:增加了HibernateUtil类以及getSessionFactory方法

package com.sinoi.util;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static SessionFactory factory;

private static Session session;

private HibernateUtil() {

}

public static SessionFactory getSessionFactory() {

if (factory == null) {

factory = new Configuration().configure().buildSessionFactory();

}

return factory;

}

public static Session getSession() {

if (session == null) {

return getSessionFactory().openSession();

} else {

return session;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值