0
Sponsored Links


Ad by Google
In our previous post we have seen fetching strategies supported by Hibernate. In this post we are going to show you a very simple and real time example of First Level Cache using annotation.

First Level Cache: In Hibernate first level cache means Session level cache, Session is by default first level cache so you can not ignore/disable this cache. Although hibernate provides few methods which can be used to remove/clear cached associated object from the Session.
How to Remove/Clear Object from the Session:
  1. session.evict(object);
  2. session.clear();

Lets implement the First Level Cache, Here is a Country table ER diagram we are going to use this table in our example.

Tools and Technologies we are using here:

  • JDK 7
  • Hibernate 4.3.7
  • MySql 5.1.10
  • Eclipse Juno 4.2
  • Maven 3.2

Overview of the Project Structure:

Main Objects of this project are:
  • pom.xml
  • hibernate.cfg.xml
  • annotated pojo
  • database
Step 1. Create database script.
CREATE DATABASE `hibernate_tutorial`;

USE `hibernate_tutorial`;

/*Table structure for table `country` */

DROP TABLE IF EXISTS `country`;

CREATE TABLE `country` (
  `country_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `country_code` varchar(255) DEFAULT NULL,
  `country_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Step 2. Create a Maven Project:
Step A: Go to File->New->Other..


Step B: Select Maven Project from the select wizard.


Step C: Select project name and location from New Maven Project wizard.


Step D: Configure project, provide GroupId, artifactId etc. See the details from the screenshot.

Step E: After completion of all the above steps, now your project will looks like this screenshot.

3. Add project dependencies into pom.xml file:
Double click on your project's pom.xml file it will looks like this with very limited information.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javamakeuse</groupId>
  <artifactId>FirstLevelCache-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>FirstLevelCache-Example</name>
  <name>FirstLevelCache-Example Using Annotation</name>
  
</project>
Now add hibernate and mysql dependencies entry inside pom.xml file. Paste the below code inside the project tag of pom.xml file.
<dependencies>
  <!-- Hibernate Dependency -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.7.Final</version>
  </dependency>
  
  <!-- MySql Connector dependency -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>

 </dependencies>
Here is a complete pom.xml file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javamakeuse</groupId>
  <artifactId>FirstLevelCache-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>FirstLevelCache-Example</name>
  <name>FirstLevelCache-Example Using Annotation</name>
  
  <dependencies>
  <!-- Hibernate Dependency -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.7.Final</version>
  </dependency>
  
  <!-- MySql Connector dependency -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>

 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>
4. Create a hibernate.cfg.xml file:
Create hibernate.cfg.xml file inside src/main/resources folder.

hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
         
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="com.javamakeuse.poc.pojo.Country"/>
          
    </session-factory>
</hibernate-configuration>
Step 5. Create Country annotated class:

Country.java
package com.javamakeuse.poc.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "country")
public class Country {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "country_id")
 private long countryID;

 @Column(name = "country_name")
 private String countryName;

 @Column(name = "country_code")
 private String countryCode;

 public Country() {
 }

 public Country(String countryName, String countryCode) {
  super();
  this.countryName = countryName;
  this.countryCode = countryCode;
 }

 public String getCountryName() {
  return countryName;
 }

 public String getCountryCode() {
  return countryCode;
 }

 @Override
 public String toString() {
  return "Country [countryID=" + countryID + ", countryName="
    + countryName + ", countryCode=" + countryCode + "]";
 }

}
Step 6. Create a HibernateUtility class: HibernateUtility class to build SessionFactory via loading Configuration file.

HibernateUtility .java
package com.javamakeuse.poc.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtility {
  private static final SessionFactory sessionFactory = buildSessionFactory();
     private static SessionFactory buildSessionFactory() {
     
      Configuration configuration = new Configuration();
      configuration.configure();

      ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
      applySettings(configuration.getProperties()).buildServiceRegistry();
      SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   return sessionFactory;
     }
   
     public static SessionFactory getSessionFactory() {
         return sessionFactory;
     }
}

Step 7. Create Main.java Service class. Service class where we implemented the First Level Cache. When we load the object from the database, Hibernate will load the object from the database and keep it into the Session and if we try to load the same entity again inside the same session than it will not hit the database. It will return the object from the Session.
Main.java
package com.javamakeuse.poc.service;

import org.hibernate.Session;

import com.javamakeuse.poc.pojo.Country;
import com.javamakeuse.poc.util.HibernateUtility;

public class Main {
 public static void main(String[] args) {
  Session session = HibernateUtility.getSessionFactory().openSession();

  session.beginTransaction();

  Country country = null;

  country = (Country) session.load(Country.class, 1l);

  System.out.println("Country from the Database => " + country);
  System.out.println();

  System.out.println("Going to print Country *** from First Level Cache");
  // second time loading same entity from the first level cache
  country = (Country) session.load(Country.class, 1l);
  System.out.println(country);

  // removing country object from the first level cache.
  session.evict(country);
  System.out.println("Object removed from the First Level Cache");
  System.out.println();

  System.out.println("Going to print Country from Database");
  country = (Country) session.load(Country.class, 1l);
  System.out.println(country);

  session.getTransaction().commit();

 }
}

Run Main class, It will print the out put at your console.

OUT PUT:
Hibernate: 
    select
        country0_.country_id as country_1_0_0_,
        country0_.country_code as country_2_0_0_,
        country0_.country_name as country_3_0_0_ 
    from
        country country0_ 
    where
        country0_.country_id=?
Country from the Database => Country [countryID=1, countryName=Australiya, countryCode=+61]

Going to print Country *** from First Level Cache
Country [countryID=1, countryName=Australiya, countryCode=+61]
Object removed from the First Level Cache

Going to print Country from Database
Hibernate: 
    select
        country0_.country_id as country_1_0_0_,
        country0_.country_code as country_2_0_0_,
        country0_.country_name as country_3_0_0_ 
    from
        country country0_ 
    where
        country0_.country_id=?
Country [countryID=1, countryName=Australiya, countryCode=+61]

From the out put, we have loaded three times the same object, but exactly two sql statement is executed. If object is already exist in the session than hibernate will not hit the database, It will return the object from the Session only.

Download the complete example from here Source Code


Sponsored Links

0 comments:

Post a Comment