Spring4学习笔记(九):JDBCTemplate

来源:互联网 发布:java ftp 编辑:程序博客网 时间:2024/04/28 18:18

1、c3p0.jar和对应的mchange-common.jar包导入正确
导入11个spring的必要包
2、编写db.properties属性文件

jdbc.user=rootjdbc.password=123456jdbc.driverClass=com.mysql.jdbc.Driverjdbc.jdbcUrl=jdbc:mysql://localhost:3306/springjdbc.initPoolsize=5jdbc.maxPoolsize=10

3、编写applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:p="http://www.springframework.org/schema/p"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">    <!-- 扫描包 -->    <context:component-scan base-package="com.whiteblack"></context:component-scan>    <!-- 导入资源文件 -->    <context:property-placeholder location="classpath:db.properties"/>    <!-- 配置C3P0数据源 -->    <bean id="dataSource"        class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="user" value="${jdbc.user}"></property>        <property name="password" value="${jdbc.password}"></property>        <property name="driverClass" value="${jdbc.driverClass}"></property>        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>        <property name="initialPoolSize" value="${jdbc.initPoolsize}"></property>        <property name="maxPoolSize" value="${jdbc.maxPoolsize}"></property>        </bean>    <!-- 配置Spring 的JdbcTemplate -->    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource"></property>    </bean></beans>

4、编写测试

public class JDBCTest {    private ApplicationContext ctx = null;      private JdbcTemplate jdbcTemplate;      private NamedParameterJdbcTemplate namedPJT;    {        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");          jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");        namedPJT = ctx.getBean(NamedParameterJdbcTemplate.class);    }    /**     *1.Sql语句中的参数名和类的属性一致     *2.使用SqlParameterSource 的BeanPropertySqlParameterSource 实现类作为参数      */    @Test    public void testNamedParameterJdbcTemplate2(){        String sql = "INSERT INTO employee(last_name,email,dept_id)"                + "VALUES(:lastName,:email,:deptId)";        Employee employee = new Employee();        employee.setLastName("XT");        employee.setEmail("xy@qq.com");        employee.setDeptId(2);        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(employee);        namedPJT.update(sql, paramSource);    }    /**     * 使用具名参数时可以使用update(String sql,SqlParameterSource paramSource)方法进行更新操作     *      * 可以给参数起名字,多个参数时维护性更高,但是麻烦     */    @Test    public void testNamedParameterJdbcTemplate(){        String sql = "INSERT INTO employee(last_name, email, dept_id) VALUES(:ln,:email,:deptid)";        Map<String, Object> paramMap = new HashMap<>();        paramMap.put("ln", "FF");        paramMap.put("email", "ff@qq.com");        paramMap.put("deptid", 1);        namedPJT.update(sql,paramMap);    }//  @Test//  public void testDelete(){//      //      String sql = "DELETE FROM employee where id > ?";//      jdbcTemplate.update(sql, 6);//  }    /**     * 获取单个列的值便于统计     * 使用.queryForObject(String sql, Class<Long> requiredType) throws DataAccessException     */    @Test    public void testQueryForCount(){        String sql = "SELECT count(id) FROM employee";        long count = jdbcTemplate.queryForObject(sql, Long.class);        System.out.println(count);    }    /**     * 查到实体类对象的集合     */    @Test    public void testQueryForList(){        String sql = "SELECT id,last_name lastName,email from employee where id > ?";        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);        List<Employee> employees = jdbcTemplate.query(sql, rowMapper , 6);        System.out.println(employees);    }    /**     * 从数据库获取一条记录,实际得到一个对象     * 注意是调用queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)方法     * 1.其中RowMapper 指定如何去映射结果集的行,常用的实现类BeanPropertyRowMapper<>     * 2.使用SQL列名的别名实现类属性的映射     * 3.不支持级联属性,不是ORM框架     */    @Test    public void testQueryForObject()    {        String sql = "SELECT id,last_name lastName,email from employee where id = ?";        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);        Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);        System.out.println(employee);    }    /**     * 执行批量的更新     * 最后一个参数是Object[] 的List 类型:因为修改一条记录需要一个Object[] ,那么多条不就是使用数组的集合     */    @Test    public void testBatchUpdate(){        String sql = "INSERT INTO employee(last_name,email,dept_id) VALUES(?,?,?)";        List<Object[]> batchArgs = new ArrayList<>();        batchArgs.add(new Object[]{"AA","aa@mail",1});        batchArgs.add(new Object[]{"BB","bb@mail",2});        batchArgs.add(new Object[]{"CC","cc@mail",3});        batchArgs.add(new Object[]{"DD","dd@mail",4});        jdbcTemplate.batchUpdate(sql, batchArgs);    }    /**     * 执行INSERT,UPDATE,DELETE语句     *      */    @Test    public void testUpdate(){        String sql = "UPDATE t_book SET b_stock = ? WHERE b_number = ?";        jdbcTemplate.update(sql, 5, 1002);    }    //测试是否数据源是否配置成功    @Test    public void testDataSource() throws SQLException {        DataSource dataSource = (DataSource) ctx.getBean("dataSource");        System.out.println(dataSource.getConnection());    }}
0 0
原创粉丝点击