当前位置: 首页 > 知识库问答 >
问题:

Hibernate缓存错误

翟光赫
2023-03-14

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; 
    } 
    }
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(); 
} 
} 
} 
<?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>
<?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> 
<?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文件无法发布,所以我不得不在<和>之间留出空格,对此表示歉意。
期待清除此错误。
提前致谢:-)

共有1个答案

况承福
2023-03-14

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

二级缓存配置:

<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
 类似资料:
  • 问题内容: 我该如何决定使用哪个? , , , 。 我阅读了https://www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/CacheConcurrencyStrategy.html,但没有足够详细地解释。 问题答案: 在Hibernate文档确实在他们定义了很好的工作: 19.2.2。策略:只读 如果您的应用程序需要读取而不是修改持久类

  • 问题内容: 我正在寻找一个简单,完整,简明的缓存列表,您将在使用Hibernate编码JPA时运行该缓存。 特别是,我想了解每个缓存的生命周期(缓存何时失效),缓存的范围,清除缓存的方式(如果有),缓存的内容(如果缓存是)。默认情况下处于打开状态,如何打开/关闭它以及任何有用的信息。 我试图在另一个问题中找到此信息,但找不到任何完整的答案。答案也遍布Hibernate文档,但是我也很难在那找到它们

  • 问题内容: 我想在hibernate项目中使用二级缓存,但是我只对hibernate二级缓存了解一点,任何人都可以解释我应该如何在代码中使用它以及需要什么配置和.jar文件吗?我将这些设置设置为我的hibernate.cfg.xml文件 并添加这些jar文件, 我想知道我是否需要更改其他配置? 我怎么知道我的项目使用二级缓存? 如果只是设置此设置,hibernate将自动使用此设置,否则我必须在我

  • 主要内容:缓存,Hibernate 一级缓存,快照区Hibernate 是一款全自动 ORM 框架,它会在应用程序访问数据时,自动生成 SQL 语句并执行,因此开发人员不需要自己编写 SQL 语句,但这也造成它无法像 MyBatis 一样,能够直接从 SQL 层面严格控制其执行性能以及对数据库的访问频率,所以很容易出现性能不佳的情况。 为此,Hibernate 提供了多种性能优化手段(例如 HQL、懒加载策略、抓取策略以及缓存机制),其中缓存机制是

  • 问题内容: 我正在开发hibernate+ ehcache程序。 ehcache.xml 我在bean.xml中提到了ehcache 我在dao类中的调用方法是 输出为: 但是它在数据库中命中了两次。我在代码中没有发现任何错误。请向我建议为什么它在数据库中命中了两次。 问题答案: 我已经解决了我的问题。我需要添加 在域类中。

  • 我已经阅读了很多资料,但对于hibernate二级缓存,我无法消除一个疑问。 1) 比方说,我有一个返回1000条记录的查询。(例如,从年龄 2) 场景2。假设我执行查询(例如,从年龄