我是hibernate的新手,并尝试使用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>
答案 0 :(得分:0)
嗨Vijay,
我认为您尚未在Hibernate Mapping文件的 hibernate.cfg.xml file
和使用类型中为缓存提供程序类提供设置。
检查代码中的以下几点: -
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)在 hibernate映射文件中添加使用情况设置
<cache usage="read-only" />
c)制作一个名为 ehcache.xml
的额外.xml文件,并将以下代码保存到其中。
<?xml version="1.0"?>
<ehcache>
<defaultCache maxElementsInMemory="100" eternal="true"/>
</ehcache>