Java Reference
In-Depth Information
A JDBC template requires a data source to be set. You can inject this property by either a setter
method or a constructor argument. Then, you can inject this JDBC template into your DAO.
<beans ...>
...
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="vehicleDao"
class="com.apress.springenterpriserecipes.vehicle.JdbcVehicleDao">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans>
Extending the JdbcDaoSupport Class
The org.springframework.jdbc.core.support.JdbcDaoSupport class has a setDataSource() method and
a setJdbcTemplate() method. Your DAO class can extend this class to have these methods inherited.
Then you can either inject a JDBC template directly or inject a data source for it to create a JDBC
template. The following code fragment is taken from Spring's JdbcDaoSupport class:
package org.springframework.jdbc.core.support;
...
public abstract class JdbcDaoSupport extends DaoSupport {
private JdbcTemplate jdbcTemplate;
public final void setDataSource(DataSource dataSource) {
if( this.jdbcTemplate == null || dataSource != this.jdbcTemplate.
getDataSource() ){
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
...
}
In your DAO methods, you can simply call the getJdbcTemplate() method to retrieve the JDBC
template. You also have to delete the dataSource and jdbcTemplate properties, as well as their setter
methods, from your DAO class because they have already been inherited. Again, for simplicity's sake,
only the change to the insert() method is shown.
Search WWH ::




Custom Search