Wednesday 27 January 2016

Hibernate HikariCP example

HikariCP is a “zero-overhead” production-quality connection pool. In this post, I am going to integrate hibernate with HikariCP.

Connection Pooling
Connection pool maintains a cache of database connections, it maintaings some number of database connection objects these can be reused, when application require new database connection object. Connection pooling is supported by IBM DB2, Microsoft SQL Server, Oracle,MySQL, and PostgreSQL etc.,

Why Connection pool is required?
Creating and opening a connection to database for every request is a time consuming process. By using connection pool, once the connection is created we can place it in the connection pool, and can use it whenever we require. 

Following are some of the libraries that provide support for connection pooling
HikariCP, HikariCP, C3P0, Apache DBCP etc., following link provides summary of open source connection pools.

Following step-by-step procedure guide you to setup complete working application in Eclipse.

Step 1: Create new project ‘hibernate_hiakricp’ in Eclipse.

Step 2: Mavenize the project. Right click on the project -> Configure -> Convert To Maven Project.

Step 3: Update pom.xml for maven dependencies.

pom.xml
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>4.3.11.Final</version>
</dependency>
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-hikaricp</artifactId>
 <version>4.3.11.Final</version>
</dependency>
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.36</version>
</dependency>

Step 4: Create package com.sample, and define the class Employee.


Employee.java
package com.sample;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;

@Entity(name = "employee")
public class Employee {
 @Id
 @TableGenerator(name = "empId", table = "employeeIdTable", pkColumnName = "empKey", pkColumnValue = "empValue", allocationSize = 1)
 @GeneratedValue(strategy = GenerationType.TABLE, generator = "empId")
 private int id;
 private String firstName;
 private String lastName;

 public Employee() {

 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}


Step 5: Create hibernate.cfg.xml and update it likes below. Make sure hibernate.cfg.xml file is in classpath.

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

 <session-factory>
  <!-- Enable the logging of all the generated SQL statements to the console -->
  <property name="show_sql">true</property>

  <!-- Format the generated SQL statement to make it more readable, -->
  <property name="format_sql">false</property>

  <!-- Hibernate will put comments inside all generated SQL statements to
  hint what’s the generated SQL trying to do -->
  <property name="use_sql_comments">true</property>

  <!-- This property makes Hibernate generate the appropriate SQL for the
  chosen database. -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

  <!-- Drop and re-create the database schema on startup -->
  <property name="hbm2ddl.auto">update</property>
  <property name="connection.release_mode">after_transaction</property>

  <!-- Hikari specific properties -->
  <property name="connection.provider_class">com.zaxxer.hikari.hibernate.HikariConnectionProvider</property>
  <property name="hikari.dataSource.cachePrepStmts">true</property>
  <property name="hikari.dataSource.prepStmtCacheSize">250</property>
  <property name="hikari.dataSource.prepStmtCacheSqlLimit">2048</property>
  <property name="hikari.dataSource.useServerPrepStmts">true</property>
  <property name="hikari.maximumPoolSize">30</property>
  <property name="hikari.idleTimeout">30000</property>

  <!-- Database connection properties -->
  <property name="hibernate.hikari.dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</property>
  <property name="hikari.dataSource.url">jdbc:mysql://127.0.0.1/sample</property>
  <property name="hikari.dataSource.user">root</property>
  <property name="hikari.dataSource.password">tiger</property>

  <!-- mappings for annotated classes -->
  <mapping class="com.sample.Employee" />
 </session-factory>

</hibernate-configuration>

Step 6: Define Main.java like below.

Main.java

package com.sample;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class Main {
 private static SessionFactory sessionFactory = getSessionFactory();

 private static SessionFactory getSessionFactory() {
  if (sessionFactory == null) {
   Configuration configuration = new Configuration().configure();
   StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
     .applySettings(configuration.getProperties());
   sessionFactory = configuration.buildSessionFactory(builder.build());
  }

  return sessionFactory;
 }

 public static void insertObject(Employee emp) {
  Session session = null;
  try {
   session = sessionFactory.openSession();
   session.beginTransaction();
   session.save(emp);
   Transaction trans = session.getTransaction();
   trans.commit();
  } catch (Exception e) {
   System.out.println(e.getMessage());
   e.printStackTrace();
  } finally {
   if (session != null)
    session.close();
  }

 }

 public static void main(String ptr[]) {
  Employee emp = new Employee();

  emp.setFirstName("ptr");
  emp.setLastName("Nayan");

  insertObject(emp);
 }
}

Step 7: Create a table in database sample.

create table employee (id integer not null, firstName varchar(255), lastName varchar(255), primary key (id));

Run Main.java, you will get following kind of output in console.

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Hibernate: select sequence_next_hi_value from hibernate_sequences where sequence_name = 'employee' for update
Hibernate: update hibernate_sequences set sequence_next_hi_value = ? where sequence_next_hi_value = ? and sequence_name = 'employee'
Hibernate: /* insert com.sample.Employee */ insert into employee (firstName, lastName, id) values (?, ?, ?)

mysql> select * from employee;
+--------+-----------+----------+
| id     | firstName | lastName |
+--------+-----------+----------+
| 163840 | ptr       | Nayan    |
+--------+-----------+----------+
1 row in set (0.00 sec)




Previous                                                 Next                                                 Home

1 comment:

  1. I want to integrate hikari cp with hibernate 3.2.5.ga, is it supported by hikari?

    ReplyDelete