Spring JDBC 【注入JdbcTemplate】

1.Dao的实现类

/**
 * 客户Dao实现类
 */
public class CustomerDaoImpl implements CustomerDao{

    /* jdbc模板,封装样板代码 */
    private JdbcTemplate jt;    // 待【注入】
    
    /* 注入模板 */
    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }

    //插入
    public void saveCustomer(Customer c) {
        String sql = "insert into customers(name,age) values(?,?)";
        jt.update(sql,new Object[]{c.getName(),c.getAge()});
        
    }

    //更新
    public void updateCustomer(Customer c) {
        String sql = "update customers set name=?,age=? where id=?";
        jt.update(sql,new Object[]{c.getName(),c.getAge(),c.getId()});
    }

    //查找
    public List<Customer> findCustomersByName(String name) {
        String sql = "select * from customers where name=?";
        return jt.query(sql, new Object[]{name}, new RowMapper(){
                @Override
                public Object mapRow(ResultSet rs, int rowNum)
                        throws SQLException {
                    Customer c = new Customer();
                    c.setId(rs.getInt("id"));
                    c.setName(rs.getString("name"));
                    c.setAge(rs.getInt("age"));
                    return c;
                }});
    }
}

 

2.Spring配置文件

<!-- 分散配置 -->
<context:property-placeholder location="jdbc/jdbc.properties"/>

<!-- c3p0数据源 -->    
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driverclass}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="maxPoolSize" value="${c3p0.pool.max.size}"/>
    <property name="minPoolSize" value="${c3p0.pool.min.size}"/>
    <property name="acquireIncrement" value="${c3p0.pool.increment}"/>
    <property name="initialPoolSize" value="${c3p0.pool.ini.size}"/>
</bean>
    
<!-- Spring 的  jdbc 模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>
    
<!-- 客户Dao -->
<bean id="customerDao" class="jdbc.CustomerDaoImpl">
    <!-- 依赖【Spring jdbcTemplate】进行操作 -->
    <property name="jt" ref="jdbcTemplate"></property>
</bean>

 

posted @ 2013-12-17 10:04  聆听自由  阅读(822)  评论(0编辑  收藏  举报