2014-11-09 147 views
0

Employee.java休眠緩存錯誤

public class Employee { 
    private int id; 
    private String firstName; 
    private String lastName; 
    private int salary; 
    public Employee() {} 
    public Employee(String fname, String lname, int salary) { 
    this.firstName = fname; 
    this.lastName = lname; 
    this.salary = salary; 
    } 
    public int getId() { 
    return id; 
    } 
    public void setId(int id) { 
    this.id = id; 
    } 
    public String getFirstName() { 
    return firstName; 
    } 
    public void setFirstName(String first_name) { 
    this.firstName = first_name; 
    } 
    public String getLastName() { 
    return lastName; 
    } 
    public void setLastName(String last_name) { 
    this.lastName = last_name; 
    } 
    public int getSalary() { 
    return salary; 
    } 
    public void setSalary(int salary) { 
    this.salary = salary; 
    } 
    } 

ManageEmployee.java(主)

import java.util.List; 

import org.hibernate.cache.*; 
import java.util.Iterator; 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction; 
import org.hibernate.SessionFactory; 
import org.hibernate.cfg.Configuration; 
public class ManageEmployee { 
private static SessionFactory factory; 
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(); 
/* Add few employee records in database */ 
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000); 
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000); 
Integer empID3 = ME.addEmployee("John", "Paul", 10000); 
/* List down all the employees */ 
//ME.listEmployees(); 
/* Update employee's records */ 
ME.updateEmployee(empID1, 5000); 
/* Delete an employee from the database */ 
//ME.deleteEmployee(empID2); 
/* List down new list of the employees */ 
ME.listEmployees(); 
} 

/* Method to CREATE an employee in the database */ 
public Integer addEmployee(String fname, String lname, int salary){ 
Session session = factory.openSession(); 
Transaction tx = null; 
Integer employeeID = null; 
try{ 
tx = session.beginTransaction(); 
Employee employee = new Employee(fname, lname, salary); 
employeeID = (Integer) session.save(employee); 
tx.commit(); 
}catch (HibernateException e) { 
if (tx!=null) tx.rollback(); 
e.printStackTrace(); 
}finally { 
session.close(); 
} 
return employeeID; 
} 

/* Method to READ all the employees */ 
public void listEmployees(){ 
Session session = factory.openSession(); 
Transaction tx = null; 
try{ 
tx = session.beginTransaction(); 
List employees = session.createQuery("FROM Employee").list(); 
for (Iterator iterator = 
employees.iterator(); iterator.hasNext();){ 
Employee employee = (Employee) iterator.next(); 
System.out.print("First Name: " + employee.getFirstName()); 
System.out.print(" Last Name: " + employee.getLastName()); 
System.out.println(" Salary: " + employee.getSalary()); 
} 
tx.commit(); 
}catch (HibernateException e) { 
if (tx!=null) tx.rollback(); 
e.printStackTrace(); 
}finally { 
session.close(); 
} 
} 

/* Method to UPDATE salary for an employee */ 
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(); 
} 
} 

/* Method to DELETE an employee from the records */ 
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(); 
} 
} 
} 

的hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?> 

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD .0//EN" 
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 


<hibernate-configuration> 
    <session-factory> 
     <!-- Database connection settings --> 
     <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver<property> 
     <property name="connection.url">jdbc:mysql://localhost:3306/test</property> 
     <property name="connection.username">********</property> 
     <property name="connection.password">********</property> 

     <!-- JDBC connection pool (use the built-in) --> 
     <property name="connection.pool_size">1</property> 

     <!-- SQL dialect --> 
     <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 

     <!-- Enable/Disable the second-level cache --> 
     <property name="cache.use_second_level_cache">true</property> 

     <!-- Specify 2nd level cache class_provider --> 
     <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </property> 


     <!-- Echo all executed SQL to stdout --> 
     <property name="show_sql">true</property> 

     <!-- Drop the existing tables and create new one --> 
     <property name="hbm2ddl.auto">create</property> 


     <!-- Mention here all the model classes along with their package name --> 
     <mapping resource="Employee.hbm.xml"/> 

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

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="Employee" table="EMPLOYEE"> 
<meta attribute="class-description"> 
This class contains the employee detail. 
</meta> 
<cache usage="read-write"/> 
<id name="id" type="int" column="id"> 
<generator class="native"/> 
</id> 
<property name="firstName" column="first_name" type="string"/> 
<property name="lastName" column="last_name" type="string"/> 
<property name="salary" column="salary" type="int"/> 
</class> 

</hibernate-mapping> 

ehcache.xml中

<?xml version="1.0" encoding="UTF-8"?> 

<diskStore path="java.io.tmpdir"/> 

<defaultCache 
maxElementsInMemory="1000" 
eternal="false" 
timeToIdleSeconds="120" 
timeToLiveSeconds="120" 
overflowToDisk="true" 
/> 

<cache name="Employee" 
maxElementsInMemory="500" 
eternal="true" 
timeToIdleSeconds="0" 
timeToLiveSeconds="0" 
overflowToDisk="false" 
/> 

錯誤

 
Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory] 
Exception in thread "main" java.lang.ExceptionInInitializerError 
    at ManageEmployee.main(ManageEmployee.java:17) 
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory] 
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:261) 
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225) 
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) 
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:295) 
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2442) 
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2438) 
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1855) 
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928) 
    at ManageEmployee.main(ManageEmployee.java:14) 
Caused by: org.hibernate.HibernateException: could not instantiate RegionFactory [net.sf.ehcache.hibernate.EhCacheRegionFactory] 
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:101) 
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:46) 
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105) 
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251) 
    ... 8 more 
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [net.sf.ehcache.hibernate.EhCacheRegionFactory] as strategy [org.hibernate.cache.spi.RegionFactory] 
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128) 
    at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:87) 
    ... 11 more

注:XML文件不可能被張貼,所以我不得不<和>和遺憾之間留出空間爲這件事。
期待清除此錯誤。
在此先感謝:-)

+0

你加入到構建路徑哪個罐子? – tigerjack89 2014-11-09 08:35:50

回答

0

我已將下面提到的罐子添加到我的hibernate項目。請讓我知道如果我錯過了這裏的東西。 ANTLR CGLIB 公地註釋 公共收集 共享記錄 的dom4j 一些休眠罐 log4j的 myaql-Java的連接器 SLF4J的API xalan的 的Xerces

4

除了如果具體罐子檢查目前,請檢查二級緩存配置。

二級緩存配置:

<property name="hibernate.cache.use_second_level_cache">true</property> 
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> 
2

的第一步是在你的項目中添加這些必須的jar:

的Ehcache-2.10.3.jarSLF4J-API 1.7。 7.jarhibernate-ehcache-5.2.10.Final.jar

並使用以下步驟將它們添加到您的構建路徑中: 選擇所有jar文件,然後右鍵單擊選擇並選擇Build Path - > Add to Build Path。

,辦理入住手續後

<property name="hibernate.cache.use_second_level_cache">true</property> 
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> 

如果你因爲那時還,它拋出了同樣的錯誤即的ExceptionInInitializerError不使用它設置的二級高速緩存屬性設置爲false。

而且,如果你正在實施二級緩存,然後嘗試使用此批註

@Cache(usage= CacheConcurrencyStrategy.READ_ONLY) 
public class Employee{ 
     ... 
     ..... 
} 
+0

在添加ehcache和hibernate ehchabe依賴項後工作 – 2017-07-20 09:48:27