springJDBC

来源:互联网 发布:python 精确除法 编辑:程序博客网 时间:2024/06/05 11:21

定义

(1)SpringJdbc是什么?

spring对jdbc的封装。
使用SpringJdbc访问数据库,不用考虑如何获取连接、关闭连接等等
繁琐的操作。

(2)编程步骤

step1.导包。
spring-webmvc,spring-jdbc, ojdbc,dbcp
step2.添加Spring配置文件。
step3.配置JdbcTemplate。 

<util:properties id="db" location="classpath:db.properties"/>    <!-- 配置连接池 -->    <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">        <property name="driverClassName"        value="#{db.driver}"/>        <property name="url"        value="#{db.url}"/>        <property name="username"        value="#{db.user}"/>        <property name="password"        value="#{db.pwd}"/>        <property name="initialSize"        value="#{db.initsize}"/>    </bean>    <bean id="jt"     class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource"        ref="ds"/>    </bean>    <context:component-scan base-package="dao"/>
@Repository("empDAO")public class EmployeeDAO {    @Autowired    @Qualifier("jt")    private JdbcTemplate jt;    public void save(Employee e){        String sql = "INSERT INTO "        + "t_emp VALUES("        + "t_emp_seq.nextval,?,?,?)";        Object[] args = {e.getName(),                e.getSalary(),e.getAge()};        jt.update(sql, args);    }    public List<Employee> findAll(){        String sql = "SELECT * FROM t_emp";        return jt.query(sql, new EmpRowMapper());    }    public Employee findById(int id){        String sql = "SELECT * FROM t_emp "                + "WHERE id = ?";        Object[] args = {id};        Employee e;        try{            e = jt.queryForObject(                    sql, args,new EmpRowMapper());        }catch(EmptyResultDataAccessException                e1){            return null;        }        return e;      }    /*     * 封装了对ResultSet的处理。     */    class EmpRowMapper implements         RowMapper<Employee>{        //index:正在被处理的记录的下标         public Employee mapRow(                ResultSet rs, int index)                     throws SQLException {            Employee e = new Employee();            e.setId(rs.getInt("id"));            e.setName(rs.getString("name"));            e.setSalary(rs.getDouble("salary"));            e.setAge(rs.getInt("age"));            return e;        }    }}

这里写图片描述
这里写图片描述

总结:将连接池注入到JdbcTemplate中,在通过id,将JdbcTemplate (jt)对象注入到xxxDao中。通过JdbcTemplate 提供的API对数据库进行操作
原创粉丝点击