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(Main)
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文件无法发布,因此我必须在&lt;之间留出空间。和&gt;抱歉这件事。
期待清除此错误。
在此先感谢: - )
答案 0 :(得分:5)
除了检查特定的jar是否存在外,请检查二级缓存配置。
二级缓存配置:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
答案 1 :(得分:2)
第一步是在项目中添加这些必需的jar:
ehcache-2.10.3.jar , slf4j-api-1.7.7.jar 和 hibernate-ehcache-5.2.10.Final.jar < / strong>
并使用以下步骤将这些添加到您的构建路径: 选择所有jar文件,然后右键单击选择并选择Build Path - &gt;添加到构建路径。
之后检查
<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{
...
.....
}
答案 2 :(得分:0)
我已将下面提到的jar添加到我的hibernate项目中。如果我在这里错过了什么,请告诉我。 ANTLR CGLIB 公地注解 公共收集 共享记录 DOM4J 一些休眠罐子 log4j的 myaql-java的连接器 SLF4J的API xalan的 的xerces