Updated April 5, 2023
Introduction to Caching in Hibernate
To match up with the pace of fast moving world, hibernate came with an innovative way to fetch the data from database quickier via simple technique of caching. We encounter caching often in respect to internet browsers where we find data stored in cache and thus helps in loading the web page bit faster. Caching is a way of storing most frequently used data files in a temporary fast processing memory. This technique enhances the system performance by reducing the time to fetch the most frequently used data.
Talking about hibernate caching, cache is a memory buffer present as a link between application and database layer to store recently used data. This saves time as we application do not have to go and hit the database server to fetch the data from tables as it is readily present in cache. It is important to have org.hibernate.cache.CacheProvider implementing before using caching in hibernate. Hibernate uses multilevel caching technique called as first level and second level caching.
Types of Caching in Hibernate
Hibernate uses multilevel caching to provide fast and smooth data loading.
To enable this facility there are three types of caching available in hibernate:
- First-Level Caching
- Second-Level Caching
- Query-Level Caching
1. First-Level Caching
This caching is also called as “session cache”. This is a mandatory cache which is present by default in hibernate. All the request objects passes through this cache. This cache can be utilized by application by sending many session objects. All the cache objects will be stored until one session is open. Database tries to minimize the number of hits to database in case there are many update statements commanded using session cache. Once the session is ended this cache is also cleared and the objects its holding are persisted, committed or disappeared without any updating depending upon the time of session closing.
2. Second-Level Caching
This is an optional caching against the previous type of cache and used in case application could not locate inspected data in the first level cache. If data is missed from first level cache then that data entity is being looked up in second level cache. But in case data is not present in either of them then the data is fetched form database.
Important thing to note here is every time the data is fetched from database then the data is stored in first and second level cache and same happens when data is fetched using second level cache then data is stored in first level cache so that is there is same query later then the miss can be avoided. It has a global scope and this can be used across different sessions created using session factory. Once session factory is closed all the related sessions will die and so the objects liked to sessions in second level cache will also vanish.
3. Query-Level Caching
This is an optional caching which requires more physical cache memory to be added to the setup. In case we have some complex data intensive queries running at the regular interval of times which require to fetch data using same parameters then we can have this cache added to our system to fasten the query results as these results will be stored already in query cache.
Example of Caching in Hibernate
Given below is the example mentioned:
There are multiple files involved to create an end to end project of hibernate caching as it requires config and main files to be created.
The steps to create a java project on hibernate caching should have these followed steps:
- Install eclipse Kepler or any latest version having jboss libraries loaded with 107 or above JRE.
- We need to have all libraries linked to caching in our “reference libraries” folder.
- Create testhibernatecache.cfg.xml file.
This is basically a config file having all code lined to basic connection like this:
Code:
<session-factory>
.. database connection properties...
<session-factory>
- Create testhibernatecache.hbm.xml file. This is file containing the table and field names to be updated with data.
This should look like:
Code:
<hibernate-mapping>
..<class name="">...
..<id name=””>...
..<property name="">...
</hiberntae-mapping>
- Create testhibernatecache.java file. This file should be created with service register configuration in session factory.
It should have all necessary libraries imported and should have code snippet written below:
Code:
public class HibernateSessFact {
private static SessionFactory sessionFactory;
static {
try {
Configuration config = new Configuration().configure();
StandardServiceRegistryBuilder serviceRegBuild = new StandardServiceRegistryBuilder();
serviceRegBuild.applySettings(config.getProperties());
ServiceRegistry serviceReg = serviceRegistryBuilder.build();
setSessionFactory(config.buildSessionFactory(serviceReg);
} catch (HibernateException exep) {
System.err.println("Error: "+ exep.getMessage());
}
}
- Create testfetchfromdb.java file. Then we should have a POJO file which is a java bean file and should be present to implement our business logic. For ex we want to pull out the name of student from school database. So to fetch query should be present in here.
- Create mainfirstlevelcahe.java file. This is the main file containing all the first level caching related information. Here everything should be dealt in session.
For Example:
Code:
import org.hibernate.Session;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.*
public static void main(String[] args) {
final int ID_OBJ=2011
SessionFactory sessFact = HibernateSessionFactory.getSessionFactory();
Session sess = sessFact.openSession();
sess.beginTransaction();
sess.save(new School(ID_OBJ, "Test"));
sess.getTransaction().commit();
School load = (School) sess.get(School.class, ID_OBJ);
System.out.println("The name is: " + load.getName());
load.setName("Test2");
load = (School) sess.get(School.class, ID_OBJ);
System.out.println("The name is: " + load.getName());
sess.close();
}
Conclusion
There are lot of benefits attached with using caching in hibernate. It reduces the time for data fetch along with that it increases the system performance. Simple in-memory first level caching reduces the time used up to significant level itself and it comes as default and mandatory with hibernate setup. We can extend this feature by setting up second level or query level caching in hibernate. This is most effective if we have multiple hits to fetch the data having same parameters and data is fetched multiple times in a short span of time.
Recommended Articles
This is a guide to Caching in Hibernate. Here we discuss the introduction to Caching in Hibernate along with the types of caching and respective example. You may also have a look at the following articles to learn more –