Spring与JDBC的整合使用

1、JbdcTemplate,提供了编写Dao的工具类

JdbcTemplate.update("update....",参数);

2、AOP事务管理,不需要在方法中追加事务提交和回滚。

3、提供了统一的异常处理

DataAccessException

4、Spring整合JDBC的步骤

(1)引入Spring相应的jar包(ioc,aop,jdbc等),数据库驱动等,在src下添加applicationContext.xml配置文件

(2)编写实体类

(3)编写Dao组件

(4)在applicationContext.xml扫描Dao组件,并且注入JdbcTemplate对象

(5)在applicationContext.xml中注册数据源,并且将数据源注入JdbcTemplate对象中。

(1) applicationContext.xml配置如下:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="#{dbParams.user}"></property>
        <property name="password" value="#{dbParams.password}"></property>
        <property name="driverClass" value="#{dbParams.driverClass}"></property>
        <property name="jdbcUrl" value="#{dbParams.jdbcUrl}"></property>    
    </bean>
    
    <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <util:properties id="dbParams" location="classpath:db.properties">      
    </util:properties>

db.properties:

#database params
user=zlc
password=123456
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC

UserRowMapper:

public class UserRowMapper implements RowMapper<User>{

    @Override
    public User mapRow(ResultSet rs, int index) throws SQLException {
        User user = new User();
        user.setUser_name(rs.getString("user_name"));
        user.setPassword(rs.getString("password"));
        return user;
    }

}

Test:

public static void main(String[] args) {
        UserRowMapper rowMapper = new UserRowMapper();
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        JdbcTemplate template = ac.getBean("template",JdbcTemplate.class);
        Object[] params = {"1111"};
        String sql = "select * from user where user_name = ?";
        List<User> list = template.query(sql, params, rowMapper);
        for(User u : list) {
            System.out.println(u.getUser_name());
            System.out.println(u.getPassword());
        }
    }

 

posted @ 2018-08-04 20:38  梦里下起了雪  阅读(152)  评论(0编辑  收藏  举报