簡體   English   中英

休眠二級緩存配置

[英]Hibernate Second Level Caching Configurations

我是休眠的新手,正嘗試使用eh-cache進行緩存。 但是我在打印緩存統計信息時看不到緩存中的任何放置,命中和遺漏。 隨附的代碼僅供參考。 請幫助我找到正在緩存的對象的方法。

public class ManageEmployee {
    private static SessionFactory factory;
    static ObjectName object;
    private static StatisticsService stats;

    public static void main(String[] args) {
        try {
            factory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object"+ ex);
            throw new ExceptionInInitializerError(ex);
        }
        ManageEmployee ME = new ManageEmployee();
        Hashtable tb = new Hashtable();
        tb.put("type", "statistics");
        tb.put("sessionFactory", "myFinancialApp");
        try {
            object = new ObjectName("hibernate", tb);
        } catch (MalformedObjectNameException e1) {
            e1.printStackTrace();
        }
        stats = new StatisticsService();
        stats.setSessionFactory(factory);
        try {
            MBeanServerFactory.newMBeanServer().registerMBean(stats, object);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException
            | NotCompliantMBeanException e) {
            e.printStackTrace();
        }
        ManageEmployee.displayCacheStatistics();
        Integer empID1=ME.addEmployee("Vijay","G", 1000, 21, "Programmer");
        Integer empID2=ME.addEmployee("Sharath","C",5000,22,"General Manager"); 
        Integer empID3 = ME.addEmployee("Jagan", "M",10000, 22, "Fresher");
        ManageEmployee.displayCacheStatistics();
        ManageEmployee.listEmployees();

    public Integer addEmployee(String fname, String lname, int salary, int age,
        String title) {
        Session session = factory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
           tx = session.beginTransaction();
           Employee employee = new Employee(fname,lname,salary,age,title);
           employeeID = (Integer) session.save(employee);
           tx.commit();

        } catch (HibernateException e) {
            if (tx != null)
               tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return employeeID;
    }

    public static void listEmployees() {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
           tx = session.beginTransaction();
           Employee emp=new Employee();
           for(int i=0;i<100;i++){
              emp=(Employee) session.get(Employee.class, 128);
              System.out.print("First Name: " + emp.getFirstName());
              System.out.print("    Last Name: " + emp.getLastName());
              System.out.println("  Salary: " + emp.getSalary());
           }
           tx.commit();
           ManageEmployee.displayCacheStatistics();
        } catch (HibernateException e) {
           if (tx != null)
              tx.rollback();
           e.printStackTrace();
        } finally {
           session.close();
        }
    } 

    public void updateEmployee(Integer EmployeeID, int salary) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
           tx = session.beginTransaction();
           Employee employee = (Employee) session.get(Employee.class,
                EmployeeID);
           employee.setSalary(salary);
           session.update(employee);
           tx.commit();
        } catch (HibernateException e) {
           if (tx != null)
              tx.rollback();
           e.printStackTrace();
        } finally {
           session.close();
        }
    }

    public void deleteEmployee(Integer EmployeeID) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
           tx = session.beginTransaction();
           Employee employee = (Employee) session.get(Employee.class,
                EmployeeID);
           session.delete(employee);
           tx.commit();
        } catch (HibernateException e) {
           if (tx != null)
              tx.rollback();
           e.printStackTrace();
        } finally {
           session.close();
        }
    }

    public static void displayCacheStatistics(){
        Statistics statistics = factory.getStatistics();

        double queryCacheHitCount = statistics.getQueryCacheHitCount();
        double queryCacheMissCount = statistics.getQueryCacheMissCount();
        double queryCacheHitRatio = queryCacheHitCount
            / (queryCacheHitCount + queryCacheMissCount);

        System.out.println("Hit count:"+queryCacheHitCount);
        System.out.println("Miss count:"+queryCacheMissCount);
        System.out.println("Cache Hit ratio:"+queryCacheHitRatio);
        // log.info("Query Hit ratio:" + queryCacheHitRatio);

        EntityStatistics entityStats =                    stats.getEntityStatistics(Employee.class.getName());
        long changes = entityStats.getInsertCount() + entityStats.getUpdateCount() + entityStats.getDeleteCount();
        System.out.println("Total changes: "+changes);
        System.out.println("Insert count: "+entityStats.getInsertCount());
        System.out.println("Update count: "+entityStats.getUpdateCount());
        System.out.println("Delete count: "+entityStats.getDeleteCount());
        System.out.println("Load count: "+entityStats.getLoadCount());
       }
    }



    <!--Employee.hbm.xml  -->
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD//EN"
       "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

    <hibernate-mapping>
    <class name="com.highradius.pojo.Employee" table="Employee">
    <cache usage="read-write" />
    <id name="id" type="int" column="employee_id">
     <generator class="identity"/>
    </id>
    <property name="firstName" column="first_name" type="string"/>
    <property name="lastName" column="last_name" type="string"/>
    <property name="salary" column="salary" type="int"/>
    <property name="title" column="title" type="string"/>
    <property name="age" column="age" type="int"/>
    </class>
    </hibernate-mapping>



    <!--ehcache.xml  -->
    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache>
    <diskStore path="java.io.tmp"/>
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU"
        />
    </ehcache>

    <!--hibernate.cfg.xml  -->
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-configuration SYSTEM 
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

    <hibernate-configuration>
    <session-factory>
    <property name="hibernate.dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
    </property>

    <!-- Assume test is the database name -->
    <property name="hibernate.connection.url">
        jdbc:mysql://localhost/Employee
    </property>
    <property name="hibernate.connection.username">
        root
    </property>
    <property name="hibernate.connection.password">

    </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.use_query_cache">true</property>
    <property name="hibernate.generate_statistics">true</property>
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
    <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
    <property name="hibernate.cache.use_structured_entries">true</property>

    <!-- List of XML mapping files -->
    <mapping resource="Employee.hbm.xml" />

    </session-factory>
    </hibernate-configuration>

嗨,維傑,

我認為您沒有在hibernate.cfg.xml file為緩存提供程序類提供設置,在Hibernate Mapping文件中沒有提供使用類型。

檢查代碼中的以下幾點:

a)將這些行放在hibernate.cfg.xml file

<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
<property name="hibernate.cache.use_second_level_cache">true</property>

b)休眠映射文件中添加使用情況設置

<cache usage="read-only" />

c)制作一個名為ehcache.xml額外.xml文件,並將以下代碼保存到其中。

<?xml version="1.0"?>  
<ehcache>
<defaultCache maxElementsInMemory="100" eternal="true"/>  
</ehcache>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM