Java Reference
In-Depth Information
3-3. Simplifying JDBC Template Creation
It's not efficient to create a new instance of JdbcTemplate every time you use it because you have to
repeat the creation statement and incur the cost of creating a new object.
The JdbcTemplate class is designed to be thread-safe, so you can declare a single instance of it in the IoC
container and inject this instance into all your DAO instances. Furthermore, the Spring JDBC framework
offers a convenient class,, to simplify your
DAO implementation. This class declares a jdbcTemplate property, which can be injected from the IoC
container or created automatically from a data source [e.g., JdbcTemplate jdbcTemplate = new
JdbcTemplate(dataSource) ]. Your DAO can extend this class to have this property inherited.
How It Works
Injecting a JDBC Template
Until now, you have created a new instance of JdbcTemplate in each DAO method. Actually, you can
have it injected at the class level and use this injected instance in all DAO methods. For simplicity's sake,
the following code shows only the change to the insert() method:
package com.apress.springenterpriserecipes.vehicle;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcVehicleDao implements VehicleDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
public void insert(final Vehicle vehicle) {
+ "VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, new Object[] { vehicle.getVehicleNo(),
vehicle.getColor(), vehicle.getWheel(), vehicle.getSeat() });
Search WWH ::

Custom Search