Azan Momin
Azan Momin

Reputation: 23

Hibernate Cache error

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

ERROR

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

NOTE: The XML file couldnt be posted so I had to leave space between < and > and sorry for this thing.
Looking forward to get this error cleared.
Thanks in advance :-)

Upvotes: 0

Views: 7574

Answers (3)

Stuti Verma
Stuti Verma

Reputation: 1069

The first step is to add these required jars in your project:

ehcache-2.10.3.jar, slf4j-api-1.7.7.jar and hibernate-ehcache-5.2.10.Final.jar

and add these to your build path using following steps: Select all the jar files, then right click on selection and select Build Path -> Add to Build Path.

After that check for

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

Set the second level cache property to false if you are not using it because then also, it throws the same error i.e. ExceptionInInitializerError.

And, if you're implementing second-level cache, then try to use this annotation

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

Upvotes: 2

Gaurav
Gaurav

Reputation: 1567

Apart from checking if the specific jars are present, check the second level cache configuration.

Second level cache configuration :

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

Upvotes: 5

Azan Momin
Azan Momin

Reputation: 23

I have added the below mentioned jars to my hibernate project. Please let me know if I am missing out something in here. antlr cglib commons-annotations commons-collection commons-logging dom4j some hibernate jars log4j myaql-java-connector slf4j-api xalan xerces

Upvotes: 0

Related Questions