Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate4 C3P0 Hibernate

Related Tutorials


 
 

Share on Google+Share on Google+

C3P0 Hibernate

Advertisement
Hibernate has its own connection pool but not suited for industrial use. In this section, you will learn how to use third party connection pool C3P0 with Hibernate.

C3P0 Hibernate

Hibernate has its own connection pool  but not suited for industrial use. In this section, you will learn how to use third party connection pool C3P0 with Hibernate.

Connection pool is the cache of the database connections recently used , which reuses the connection when the future reconnection request comes in future. In this way it reduces the cost of opening and closing of database since opening and closing is expensive process.

You can download C3P0 jar file from here.

EXAMPLE

In the below example, we will configure C3P0 in hibernate.cfg.xml as follows :

<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.13:3306/anky</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>

<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property> 

<mapping class="net.roseindia.Worker"/>

</session-factory>
</hibernate-configuration>

The functions of C3P0 property tag is given below :

C3P0 Tag Function Hibernate Default
hibernate.c3p0.min_size Sets the minimum number of JDBC connection in the pool. 1
hibernate.c3p0.max_size Sets the maximum number of JDBC connection in the pool. 100
hibernate.c3p0.timeout Sets the idle connection timeout time/ removal time period(in seconds). 0, never expire
hibernate.c3p0.max_statements Number/Count of maximum prepared statement which will cached 0, caching is disabled.
hibernate.c3p0.idle_test_period Sets the idle time in seconds before a connection is automatically validated. 0

The rest of the project code is given below :

The project hierarchy and the jar file used is given below :

The query used to create worker table is given below :

CREATE TABLE `worker` ( 
`worker_id` bigint(10) NOT NULL auto_increment, 
`firstname` varchar(50) default NULL, 
`lastname` varchar(50) default NULL, 
`birth_date` date NOT NULL, 
`cell_phone` varchar(15) NOT NULL, 
PRIMARY KEY (`worker_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

Worker.java

package net.roseindia;

import java.util.Date;

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

@Entity
@Table(name = "worker")
public class Worker {

@Id
@GeneratedValue
@Column(name = "worker_id")
private Long workerId;



@Column(name = "firstname")
private String firstname;

@Column(name = "lastname")
private String lastname;

@Column(name = "birth_date")
private Date birthDate;

@Column(name = "cell_phone")
private String cellphone;

public Worker() {

}

public Worker(String firstname, String lastname, Date birthdate,
String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = birthdate;
this.cellphone = phone;

}

public Long getWorkerId() {
return workerId;
}

public void setWorkerId(Long workerId) {
this.workerId = workerId;
}

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

public Date getBirthDate() {
return birthDate;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public String getCellphone() {
return cellphone;
}

public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
}

ManageWorker.java

package net.roseindia;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

public class ManageWorker {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = sf.openSession();
session.beginTransaction();

//For passing Date of birth as String
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dob=null;
try {
dob = sdf.parse("1987-05-21");
} catch (ParseException e) {
e.printStackTrace();
}

Worker worker = new Worker();
worker.setFirstname("Alexander");
worker.setLastname("Houstan");
worker.setBirthDate(dob);
worker.setCellphone("919595959595");
session.save(worker);

session.getTransaction().commit();
session.close();

}
}

OUTPUT

In console, you will get the following output :

Hibernate: insert into worker (birth_date, cell_phone, firstname, lastname) values (?, ?, ?, ?)

In worker table, you will get the following record

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 19, 2012

Related Tutorials

Discuss: C3P0 Hibernate  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com