Using Datasource in Spring

Finally I have managed to use a datasource in spring. My database is called AKDB, which was created in Oracle Database11gR2. To use this database as a datasource, heres what I have done in my app :

First, I created a jdbc.properties file. In the file I put in the jdbc connection details which I received from my weblogic as follows :

jdbc.driverClassName=oracle.jdbc.xa.client.OracleXADataSource
jdbc.url=jdbc:oracle:thin:@localhost:1521:AKDB
jdbc.username=username
jdbc.password=password

Now in the spring bean definitions file, namely the dispatcher-servlet.xml in my case, I have defined the beans to use these data as :

<bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

Here I have the property configurer to read the properties file that I created. This ensures that spring recognises the file as key-value pair, where the key is called placeholders in this context. 

    <bean id="dataSource" name="loginappdatasource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
        p:username="${jdbc.username}" p:password="${jdbc.password}" />

Here, I am defining the bean called loginappdatasource of type DriverManagerDataSource using the data from the properties file, accessed using the keys/placeholders.

    <bean name="loginDaoImpl" class="com.loginapp.dao.impl.LoginDaoImpl">
        <property name="dataSource" ref="loginappdatasource"/>
    </bean>   

Here I am injecting the datasource bean into my Dao class. Here I resorted to the classic setter injection as I am yet to figure out how to use annotations for the same. Once this is done, the datasource property can be used to take connections from as :

Connection connection = dataSource.getConnection();

The rest is classic jdbc stuff now that you have the connection to the database. I have heard that instead of the DriverManagerDataSource, we can use connection pooling thru JNDI. My next mission is to figure that part out Smile

More From Author

The closest thing to replace pen and paper for good :)

I have used two other styluses namely, the Bamboo Stylus and the Cregle iPen. By…

Apple Event October 2012

Been watching the live streaming of the Oct 23rd apple event. This is the event where…

Bootcamping Windows 8

Finally installed Windows 8 to Bootcamp(to non-mac users, this means that the windows now runs…

Leave a Reply

Your email address will not be published. Required fields are marked *