Share on Google+Share on Google+

Spring data source C3P0

In this section, we will discuss about Spring data source C3P0 and it's implementation with example.

Spring data source C3P0

In Spring , we connect to a database via data source. When we are using jdbc layer in Spring , JNDI provide us data source or you can configure your own data source by implementing connection pool , provided by a third party. One of the most famous implementations are Apache Jakarta Commons DBCP and C3P0.The "DriverManagerDataSource" perform poorly when multiple requests for a connection are made.

In the below example , we are using data source c3p0 to create a database table & insert value using jdbcTemplate. You can download c3p0 from below given link :

C3P0 Configuration (xml file):

<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<context:property-placeholder location=""/>

package net.roseindia;

import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class CreateTable {
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);

    public void doExecute() {
    this.jdbcTemplate.execute("create table mytable(id integer, name varchar(100))");
    public void doInsert() {
    this.jdbcTemplate.update("insert into mytable(id, name) values (?, ?)",1, "Ankit");

package net.roseindia;

import org.springframework.beans.factory.xml.XmlBeanFactory;


public class MainCreateTable {

public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("DataTable.xml")) ;

CreateTable myBean =(CreateTable) beanFactory.getBean("CreateTable");


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
xmlns:xsi="" xmlns:context=""
<bean id="CreateTable" class="net.roseindia.CreateTable">
<property name="dataSource" ref="dataSource" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://" />
<property name="user" value="root" />
<property name="password" value="root" />
<context:property-placeholder location="" />


Console Message (eclipse) :


Mysql :

Download Source Code


Posted on: August 20, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.


Advertisement null