Hibernate4二级缓存Ehcache配置

本文详细介绍了如何在Hibernate中配置并使用EHCache作为二级缓存,包括必要的配置文件设置及测试代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文转载自:http://blog.youkuaiyun.com/chaoowang/article/details/21236501
原处的ehcache.xml少添加了文件,也是进过错误信息看出的,加上了配置。
源码下载
hibernate使用版本是:hibernate-release-4.3.11.Final
需要的jar包:hibernate-release-4.3.11Final\lib\required下所有jar包
ehcache jar包:hibernate-release-4.3.11.Final\lib\optional\ehcache下所有包
junit:junit-4.12.jar和MySQL-connector-Java-5.1.39-bin.jar
注:hibernate 4.2.5版本ehcache缓存不依赖commons-logging-1.1.1.jar,需要的是slf4j-api-1.6.1.jar
这里写图片描述
这里写图片描述
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>  
        <!-- Database connection settings -->  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate4cache</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">root</property>  
        <!-- JDBC connection pool (use the built-in) -->  
        <property name="connection.pool_size">1</property>  
        <!-- SQL dialect -->  
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>  
        <!-- Enable Hibernate's automatic session context management -->  
        <property name="current_session_context_class">thread</property>  
        <!-- Disable the second-level cache -->  
        <!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> 
        -->  
        <!-- 配置二级缓存 -->  
        <property name="hibernate.cache.use_second_level_cache">true</property>  
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>  
        <!-- hibernate3的二级缓存配置 -->  
        <!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->  
        <!-- 开启查询缓存 -->  
        <property name="hibernate.cache.use_query_cache">true</property>  

        <!-- Echo all executed SQL to stdout -->  
        <property name="show_sql">true</property>  
        <!-- Drop and re-create the database schema on startup -->  
        <property name="hbm2ddl.auto">update</property>  

        <mapping class="com.zhenqi.pojo.User" />  
    </session-factory>  
</hibernate-configuration> 

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">  
    <!--  
        name:cache唯一标识   
        eternal:缓存是否永久有效   
        maxElementsInMemory:内存中最大缓存对象数  
        overflowToDisk(true,false):缓存对象达到最大数后,将缓存写到硬盘中  
        diskPersistent:硬盘持久化  
        timeToIdleSeconds:缓存清除时间   
        timeToLiveSeconds:缓存存活时间  
        memoryStoreEvictionPolicy:缓存清空策略  
        1.FIFO:first in first out 先讲先出  
        2.LFU: Less Frequently Used 一直以来最少被使用的  
        3.LRU:Least Recently Used  最近最少使用的  
    -->  
    <defaultCache maxElementsInMemory="1000" eternal="false"  
        timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />  

    <cache name="com.zhenqi.pojo.User" eternal="false" maxElementsInMemory="1000"  
        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="3600"  
        timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" />  
</ehcache>  

User实体类

package com.zhenqi.pojo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private int age;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

UserTest测试类:

package com.zhenqi.pojo;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.BeforeClass;
import org.junit.Test;

public class UserTest {

    private static SessionFactory sessionFactory = null;

    @BeforeClass
    public static void beforeClass() {
        Configuration configuration = new Configuration();
        try {
            configuration.configure();
        } catch (HibernateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                //.buildServiceRegistry();
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();

        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }

    @Test
    public void testEhcache() {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        User u1 = (User) session.load(User.class, 3);
        System.out.println(u1.getName());
        session.getTransaction().commit();
        session.close();
        Session session2 = sessionFactory.openSession();

        session2.beginTransaction();
        User u2 = (User) session2.load(User.class, 3);
        System.out.println(u2.getName());
        session2.getTransaction().commit();
        session2.close();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void testListEhcache() {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        List<User> users1 = (List<User>) session.createQuery("from User").setCacheable(true).list();
        for (User user : users1) {
            System.out.println(user.getName());
        }
        session.getTransaction().commit();
        session.close();

        Session session2 = sessionFactory.openSession();
        session2.beginTransaction();
        List<User> users2 = (List<User>) session2.createQuery("from User").setCacheable(true).list();
        for (User user : users2) {
            System.out.println(user.getName());
        }
        session2.getTransaction().commit();
        session2.close();
    }
}

测试报错:

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
十月 25, 2016 9:32:06 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
**SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.**
十月 25, 2016 9:32:06 下午 org.hibernate.cache.spi.UpdateTimestampsCache <init>
INFO: HHH000250: Starting update timestamps cache at region: org.hibernate.cache.spi.UpdateTimestampsCache
十月 25, 2016 9:32:06 下午 org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory getCache
**WARN: HHH020003: Could not find a specific ehcache configuration for cache named [org.hibernate.cache.spi.UpdateTimestampsCache]; using defaults.**

而在ehcache。xml文件加入以下配置就可以了。

<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
           maxElementsInMemory="5000" 
           eternal="true" 
           overflowToDisk="true" />
    <cache name="org.hibernate.cache.internal.StandardQueryCache"
           maxElementsInMemory="10000" 
           eternal="false" 
           timeToLiveSeconds="120"
           overflowToDisk="true" />

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值