Spring对jdbc技术提供了很好的支持。

体现在:

  1)Spring对c3p连接池的支持很完善;

  2)Spring对jdbc提供了JdbcTemplate,来简化jdbc操作;

1.使用步骤

1)引入jar文件

  spring-jdbc-3.2.5.RELEASE.jar

  spring-tx-3.2.5.RELEASE.jar

  c3p0连接池包

  数据库驱动包

2) 容器创建DataSource对象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///student"/>
        <property name="user" value="root"/>
        <property name="password" value="juaner767"/>
        <property name="initialPoolSize" value="3"/>
        <property name="maxPoolSize" value="6"/>
        <property name="maxStatements" value="100"/>
        <property name="acquireIncrement" value="2"/>
    </bean>
    <bean id="userDao" class="com.juaner.spring.jdbc.UserDao">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

3)使用连接池对象

public class UserDao {
    //注入datasorce
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void save() {
        String sql = "insert into student values( 4,'李四')";
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.executeUpdate();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.使用JdbcTemplate优化

    public void save() {
        String sql = "insert into student(name) values( '李四')";
        //使用spring优化
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update(sql);
    }

封装一个对象

        String sql1 = "select * from student";
        List<Student> query = jdbcTemplate.query(sql1, new RowMapper<Student>() {
            //如何封装一行记录
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student = new Student();
                student.setId(resultSet.getInt("id"));
                student.setName(resultSet.getString("name"));
                return student;
            }
        });

容器创建JdbcTemplate

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource"/>
    </bean>
    <bean id="userDao" class="com.juaner.spring.jdbc.UserDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

 

 posted on 2016-06-18 10:55  十三弦  阅读(678)  评论(0编辑  收藏  举报