【问题标题】:Hibernate Cache error休眠缓存错误
【发布时间】:2015-01-05 17:31:59
【问题描述】:

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" 
/> 

错误

无法创建 sessionFactory object.org.hibernate.service.spi.ServiceException:无法创建请求的服务 [org.hibernate.cache.spi.RegionFactory] 线程“主”java.lang.ExceptionInInitializerError 中的异常 在 ManageEmployee.main(ManageEmployee.java:17) 原因:org.hibernate.service.spi.ServiceException:无法创建请求的服务 [org.hibernate.cache.spi.RegionFactory] 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:261) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) 在 org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:295) 在 org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2442) 在 org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2438) 在 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1855) 在 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928) 在 ManageEmployee.main(ManageEmployee.java:14) 原因:org.hibernate.HibernateException:无法实例化 RegionFactory [net.sf.ehcache.hibernate.EhCacheRegionFactory] 在 org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:101) 在 org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:46) 在 org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251) ... 8 更多 原因:org.hibernate.boot.registry.selector.spi.StrategySelectionException:无法将名称 [net.sf.ehcache.hibernate.EhCacheRegionFactory] ​​解析为策略 [org.hibernate.cache.spi.RegionFactory] 在 org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128) 在 org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:87) ... 11 更多

注意:XML 文件无法发布,所以我不得不在 之间留出空格,对此感到抱歉。
期待解决此错误。
在此先感谢:-)

【问题讨论】:

  • 你在构建路径中添加了哪些 jar?

标签: hibernate caching


【解决方案1】:

我已将下面提到的 jar 添加到我的休眠项目中。如果我在这里遗漏了什么,请告诉我。 蚂蚁 cglib 公共注释 公共收集 公共记录 dom4j 一些冬眠罐子 日志4j myaql-java-连接器 slf4j-api 夏兰 练习

【讨论】:

    【解决方案2】:

    除了检查特定的jars是否存在外,还要检查二级缓存配置。

    二级缓存配置:

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

    【讨论】:

      【解决方案3】:

      第一步是在你的项目中添加这些所需的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>
      

      如果您不使用二级缓存属性,请将其设置为 false,因为这样也会引发相同的错误,即 ExceptionInInitializerError。

      而且,如果你正在实现二级缓存,那么尝试使用这个注解

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

      【讨论】:

      • 这在添加 ehcache 和 hibernate ehchabe 依赖项后工作
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 2012-04-29
      • 2011-11-18
      • 2017-01-16
      • 2011-06-18
      • 2011-10-13
      • 2012-03-14
      相关资源
      最近更新 更多