Saturday, January 7, 2012

How to use a Carbon JNDI data-source within a Spring Service

If you are familiar with Spring Framework, you may know that Spring Framework has provided templates to data access using JDBC and JNDI data-sources. So it's bit different how we write code to access a database or a JNDI data-source than normal JDBC connection code or JNDI lookup code within Spring Framework.

This post describes you how to access a data-source that created using WSO2 Carbon data-source component, within a Spring Service.

Following code segment shows how to make connection to a JNDI data-source using normal java program.

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); //same context factory class provided when creating JNDI data-source.
env.put(Context.PROVIDER_URL, "rmi://localhost:2195"); //same provider url provided when creating JNDI data-source.

InitialContext ctx = new InitialContext(env);
DataSource ds = (DataSource) ctx.lookup("CarbonJndiDS"); //"CarbonJndiDS" is the JNDI data-source name.

conn = ds.getConnection();

But when it comes to the Spring framework , We do not have to write above code to make connection. Instead of that we need to put some entry to bean xml of the Spring project. By adding following two bean elements to the bean xml of Spring project will do the same job that we done using the above code segment using in a normal java program.

<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
            <prop key="java.naming.factory.initial">com.sun.jndi.rmi.registry.RegistryContextFactory</prop>
            <prop key="java.naming.provider.url">rmi://localhost:2195</prop>

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jndiTemplate"/>
    <property name="jndiName" value="CarbonJndiDS"/>

In the above first bean (i.e: "jndiTemplate"), it has defined a bean property called "environment" and has provided JNDI data-source properties that used to create Carbon data-source as sub properties.
In the second bean (i.e: "dataSource"), note the "jndiName" property value. It should be the name of Carbon data-source name.

Once you create the connection to Carbon JNDI data-source using above two beans, then you can use JDBCTemplate provided by Spring framework and code to perform SQL operations.