Detailed Java hibernate framework of the cache and native SQL statements used _java

Source: Internet
Author: User
Tags generator object object rollback scalar

Hibernate cache
caching is all about the performance optimization of an application and it sits between applications and databases to avoid database access multiple times, giving performance-critical applications a better performance.

Caching is important for hibernate, which uses a multilevel caching scenario as described below:

First-level caching:
The first level cache is the session cache, a mandatory cache, through which all requests must pass. The session object constantly drives itself to the object, before submitting to the database.

If you issue multiple updates to an object, Hibernate tries to delay updating as long as possible to reduce the number of updated SQL statements issued. If you close the session, all cached objects will be lost, either persisted, or updated in the database.

Second-level caching:
The secondary cache is an optional cache and a level cache that is always consulted before any attempt is made to find an object's level two cache. The secondary cache can be configured on a per-class and per-collection basis, primarily for objects that are cached in the session.

Any third party cache can use hibernate. The Org.hibernate.cache.CacheProvider interface provides that a handle cache implementation must be implemented to provide hibernate.

Query-level caching:
Hibernate also implements the tight integration of the query result set cache with the level two cache.

This is an optional feature that requires two additional physical caches to hold cached query results and regions when a table's last updated timestamp. This is useful only for queries that run frequently with the same parameters.

Second-level caching:
Hibernate uses a level one cache, by default, you do nothing with the first level cache. Let's go directly to the optional second level cache. Not all classes benefit from caching, so it is important to disable level two caching.

The hibernate level two cache is set to two steps. First, you must decide which concurrency policy to use. After this, you can configure cache expiration and provide physical cache properties using caching.

Concurrency policy:
A concurrency policy is an intermediary's responsibility for storing data items in the cache and retrieving them from the cache. If you want to enable level two caching, you will have to decide which cache concurrency policy to use for each persisted class and collection.

Transactional: The use of this strategy for the primary reading of data in order to prevent the concurrency of outdated data is critical in newer rare cases.

Read-write: This strategy is used again primarily to read data in places to prevent concurrent transactions that stale data is critical in newer rare cases.

Nonstrict-read-write: This strategy does not guarantee consistency between the cache and the database. With this strategy, if the data is rarely changed and the likelihood of stale data is small, the key is not to pay attention.

Read-only: Concurrency policies apply to data and will never change. Use data for informational purposes only.

If we are going to use the second level cache for our employee class, let's add the mapping elements that tell hibernate to use the read-write cache policy employee instance.

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

 
 

The usage= "Read-write" property tells Hibernate to use a cache defined by a read-write concurrency policy.

Cache provider:
After considering the concurrency policy for your cached candidate class, the next step is to select a cache provider. Hibernate forces the selection of a cache to provide the entire application.

The cache is provided in the specified Hibernate.cfg.xml configuration file. Select Ehcache as the second-level cache provider:

<?xml version= "1.0" encoding= "Utf-8"?> <! DOCTYPE hibernate-configuration SYSTEM "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" > < hibernate-configuration> <session-factory> <property name= "Hibernate.dialect" > Org.hibernate.dialec
  T.mysqldialect </property> <property name= "Hibernate.connection.driver_class" > Com.mysql.jdbc.Driver </property> <!--Assume students is the database name--> <property name= "Hibernate.connection.url"
   ; Jdbc:mysql://localhost/test </property> <property name= "hibernate.connection.username" > Root </pro perty> <property name= "Hibernate.connection.password" > root123 </property> <property name= "Hibe Rnate.cache.provider_class "> Org.hibernate.cache.EhCacheProvider </property> <!--List of XML mapping Files--> <mapping resource= "Employee.hbm.xml"/> </session-factory>  

Now you need to specify the properties of the cache area. Ehcache have their own profile ehcache.xml, in the application in Classpath. The Employee class cache configuration in Ehcache.xml may look like this:

<diskstore path= "Java.io.tmpdir"/> <defaultcache maxelementsinmemory= "1000"
False "
timetoidleseconds=" timetoliveseconds= "
overflowtodisk=" "true"
/>

<cache Name= "Employee"
maxelementsinmemory= "eternal=" "
true"
timetoidleseconds= "0"
timetoliveseconds= "0"
overflowtodisk= "false"
/>

In this way, now enable the Employee class level two cache and Hibernate now level two cache, whenever browsing to an employee or when the employee is loaded through an identifier.

You should analyze all of your classes and choose the appropriate caching policy for each class. Sometimes, a level two cache can degrade the performance of an application. Therefore, it is recommended that the baseline application does not enable caching for the first time, and is ideal for caching and checking performance. If caching does not improve system performance then there is no sense in making any type of cache.

Query-level caching:
Using the query cache, you must first activate it using the Hibernate.cache.use_query_cache= "true" property configuration file. If you set this property to True, let hibernate create the desired cache in memory to hold the query and the set of identifiers.

Next, using the query cache, you can use the Setcacheable (Boolean) method of the query class. For example:

Session session = Sessionfactory.opensession ();
Query query = Session.createquery ("from EMPLOYEE");
Query.setcacheable (true);
List users = Query.list ();
Sessionfactory.closesession ();

Hibernate also supports very fine-grained cache support through the concept of a cache area. The buffer is a part of the given name cache.

Session session = Sessionfactory.opensession ();
Query query = Session.createquery ("from EMPLOYEE");
Query.setcacheable (true);
Query.setcacheregion ("employee");
List users = Query.list ();
Sessionfactory.closesession ();

This code uses methods to tell hibernate to store and find queries for employees in the cache.


Hibernate native SQL
You can use native SQL to express database queries if you want to take advantage of database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate3.x allows you to use handwritten SQL statements, including stored procedures, all creation, updates, deletes, and load operations.

The application will create a native SQL query (on the Session Interface) Createsqlquery () method from the conversation:

Public sqlquery createsqlquery (String sqlstring) throws Hibernateexception
When passing a containing SQL query to the Createsqlquery () method, you can use the SQL result with any existing hibernate entity, join, or a scalar result using the Addentity () method, Addjoin (), and Addscalar () The string that the method is associated with.

Scalar query:
The most basic SQL query is to get a scalar (numeric) list from one or more tables. The following is the value of the syntax using the native SQL scalar:

String sql = "Select first_name, Salary from EMPLOYEE";
SQLQuery query = session.createsqlquery (SQL);
Query.setresulttransformer (CRITERIA.ALIAS_TO_ENTITY_MAP);
List results = query.list ();

Entity's query:
The query above returns a scalar value, which is the "bare" data returned from the resultset. The following syntax uses the Addentity () method to obtain entity objects from native SQL queries as a whole.

String sql = "SELECT * from EMPLOYEE";
SQLQuery query = session.createsqlquery (SQL);
Query.addentity (employee.class);
List results = query.list ();

Name SQL query:
The following syntax uses the Addentity () method to obtain entity objects from native SQL queries and to use named SQL queries.

String sql = "SELECT * from EMPLOYEE WHERE id =: employee_id";
SQLQuery query = session.createsqlquery (SQL);
Query.addentity (employee.class);
Query.setparameter ("employee_id");
List results = query.list ();

Native SQL Example:
Consider the following Pojo class:

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;
  }
}

Let's create the following employee table to store the Employee object:

CREATE TABLE EMPLOYEE (
  ID INT not NULL auto_increment,
  first_name VARCHAR () default null,
  last_name varcha R () default NULL,
  salary   INT default null,
  PRIMARY KEY (ID)
);

The following will be mapped to the file.

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

 
 

Finally, we will create the application class's main () method to run, and we will use the native SQL query application:

Import java.util.*; 
Import org.hibernate.HibernateException; 
Import org.hibernate.Session;
Import org.hibernate.Transaction;
Import Org.hibernate.SessionFactory;
Import Org.hibernate.SQLQuery;
Import Org.hibernate.Criteria;
Import Org.hibernate.Hibernate;

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", 2000);
   Integer empID2 = Me.addemployee ("Daisy", "Das", 5000);
   Integer empID3 = Me.addemployee ("John", "Paul", 5000);

   Integer empID4 = Me.addemployee ("Mohd", "Yasee", 3000); /* List down employeeS and their salary using Scalar Query */me.listemployeesscalar ();
  /* List down complete employees information using Entity Query */me.listemployeesentity (); }/* method to CREATE a 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 the employees using Scalar Query */public void Listemployeesscalar () {
   Factory.opensession ();
   Transaction tx = NULL;
     try{tx = Session.begintransaction (); String sql = "Select first_name, Salary FROM EMPLOYEE ";
     SQLQuery query = session.createsqlquery (SQL);
     Query.setresulttransformer (CRITERIA.ALIAS_TO_ENTITY_MAP);

     List data = Query.list ();
      for (Object object:data) {Map row = (map) Object; 
      System.out.print ("Name:" + row.get ("first_name")); 
     System.out.println (", Salary:" + row.get ("Salary"));
   } tx.commit ();
     }catch (hibernateexception e) {if (tx!=null) Tx.rollback (); 
   E.printstacktrace (); 
   }finally {session.close (); }/* method to READ all the employees using Entity Query */public void listemployeesentity () {session Sessio
   n = factory.opensession ();
   Transaction tx = NULL;
     try{tx = Session.begintransaction ();
     String sql = "SELECT * from EMPLOYEE";
     SQLQuery query = session.createsqlquery (SQL);
     Query.addentity (Employee.class);

     List employees = query.list ();
      for (Iterator iterator = Employees.iterator (); Iterator.hasnext ();) {Employee employee = (employee) iterator.next (); 
      System.out.print ("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 ();

 }
  }
}

Compiling and executing:
Here is a step to compile and run the above application. Be sure to set path and classpath appropriately before compiling and executing.

Executes the Manageemployee binary file to run the program.

The following results are obtained, and records are created in the employee table.

$java Manageemployee
....... Various LOG MESSAGES would DISPLAY

here ... Name:zara, salary:2000-
Name:daisy, salary:5000-A-Name:john
, salary:5000-A-
NAME:MOHD , salary:3000 a
Name:zara last Name:ali salary:2000 a
name:daisy last Name:das salary:5000
T Name:john last Name:paul salary:5000-
Name:mohd last Name:yasee salary:3000

If you check the employee table, it should record the following:

Mysql> select * from EMPLOYEE;
 +----+------------+-----------+--------+ | id | first_name | last_name | salary | +---- +------------+-----------+--------+
| 26 | Zara |  Ali | 2000 | | 27 | Daisy |  Das | 5000 | | 28 | John |  Paul | 5000 | | 29 | Mohd |  Yasee |
3000 | +----+------------+-----------+--------+ 4 rows in Set (0.00 sec) 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.