Archive

Archive for May, 2009

SPRING: Datasource Configurations

Spring provides several options for making a DataSource available to your application.

1) Getting a DataSource from JNDI

<bean id=”dataSource”

class=”org.springframework.jndi.JndiObjectFactoryBean“>

<property name=”jndiName”>

<value>java:comp/env/jdbc/myDatasource</value>

</property>

</bean>

OR

<jee:jndi-lookup id=”dataSource” jndi-name=”/jdbc/RantzDatasource” resource-ref=”true” />

 

We have now wired in our server’s DataSource and its connection pooling facility

2) Creating a DataSource connection pool

<bean id=“myDataSource” class=“com.mchange.v2.c3p0.ComboPooledDataSource” destroy-method=“close”>

<property name=driverClassvalue=“net.sourceforge.jtds.jdbc.Driver” />

<property name=jdbcUrlvalue=“jdbc:jtds:sqlserver://R2DDEV2:1433/sampleDB” />

<property name=uservalue=“sa” />

<property name=passwordvalue=“dev123″ />

</bean>

We now have a DataSource with connection pooling independent of an application server.

3) Using a DataSource while testing

DriverManagerDataSource. This class can easily be configured and used with a unit test or suite of unit tests.

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName(driver);

dataSource.setUrl(url);

dataSource.setUsername(username);

dataSource.setPassword(password);

 

OR

<bean id=”dataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource“>

<property name=”driverClassName” value=” net.sourceforge.jtds.jdbc.Driver” />

<property name=”url” value=” jdbc:jtds:sqlserver://R2DDEV2:1433/sampleDB” />

<property name=”username” value=”sa” />

<property name=”password” value=”" />

</bean>

You now have a DataSource to use when testing your data access code.

Using JdbcTemplate

 

JdbcTemplate template = new JdbcTemplate(myDataSource);

All of Spring’s DAO template classes are thread-safe, we only need one JdbcTemplate instance for each DataSource in our application

<bean id=”jdbcTemplate” class=”org.springframework.jdbc.core.JdbcTemplate”>

<property name=”dataSource“><ref bean=”dataSource”/></property>

</bean>

<bean id=”studentDao” class=”StudentDaoJdbc”>

<property name=”jdbcTemplate“><ref bean=”jdbcTemplate“/></property>

</bean>

<bean id=”courseDao” class=”CourseDaoJdbc”>

<property name=”jdbcTemplate“><ref bean=”jdbcTemplate“/></property>

Follow

Get every new post delivered to your Inbox.