美文网首页
Spring使用JDBCTemplate

Spring使用JDBCTemplate

作者: BlueSkyBlue | 来源:发表于2020-03-20 13:32 被阅读0次

    使用JDBCTemplate更新数据库

    使用sql语句和参数更新数据库(update)

    public int update(String sql, Object ...args){
        throw DataAccessException;
    }
    

    批量更新数据库(batchUpdate)

    public int[] batchUpdate(String sql, List<Object[]>batchArgs)
    

    查询单行(queryForObject)

    public <T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, Object ...args){
        throw DataAccessException;
    }
    

    便利的BeanPropertyRowMapper实现

    Class ParameterizedBeanPropertyRowMapper<T>
    

    查询多行(query)

    public <T> List<T> query(String sql, ParameterizedRowMapper<T> rm, Object ...args){
        throw DataAccessException;
    }
    

    单值查询(queryForObject)

    public <T> queryForObject(String sql, Class<T> requiredType, Object ...args){
        throw DataAccessException;
    }
    

    通过JDBC连接数据库

    首先引入相关的jar包



    数据配置文件(db.properties)

    jdbc.user=postgres
    jdbc.password=******
    jdbc.driverClass=org.postgresql.Driver
    jdbc.jdbcUrl=jdbc:postgresql://localhost:5432/database
    jdbc.initPoolSize=5
    jdbc.maxPoolSize=10
    

    之后是Spring配置文件

    <context:property-placeholder location="classpath:db.properties"/>
    <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>
    

    测试类(检测我们是否可以得到数据库连接对象)

    public class JDBCTest {
    
        private ApplicationContext ctx = null;
    
        {
            ctx = new ClassPathXmlApplicationContext("application-context.xml");
        }
    
        @Test
        public void test() throws SQLException {
            DataSource dataSource = ctx.getBean(DataSource.class);
            System.out.println(dataSource.getConnection());
        }
    }
    

    测试修改操作

    首先在数据库中建立两个表



    department数据属性:



    employee数据属性:

    更改操作的代码

    @Test
    public void testUpdate(){
        String sql = "update employees set email=? where id=? ";
        jdbcTemplate.update(sql, "rhf0410@gmail.com", 1);
    }
    

    批量更改操作

    @Test
    public void testBatchUpdate(){
        String sql = "insert into employees(id, last_name, email, dept_id) values(?, ?, ?, ?) ";
        List<Object[]>args = new ArrayList<>();
        args.add(new Object[]{2, "Xu", "test0409@test.com", 1});
        args.add(new Object[]{3, "Li", "test0410@test.com", 1});
        args.add(new Object[]{4, "Hu", "test0411@test.com", 1});
        jdbcTemplate.batchUpdate(sql, args);
    }
    

    从数据库中获取其中的一个对象

    @Test
    public void testQueryForObject(){
        String sql = "select id, last_name, email from employees where id=? ";
        RowMapper<Employee>rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);
        System.out.println(employee);
    }
    
    • RowMapper指定如何去映射结果集的行,常用的实现类为BeanPropertyRowMapper。
    • 使用SQL中列的别名完成列名和类的属性名映射,例如last_name, lastName。
    • 不支持级联属性。JdbcTemplate只是JDBC的工具,不是ORM框架。

    查询数据库中的对象集合

    @Test
    public void testQueryForList(){
        String sql = "select id, last_name, email from employees where id > ? ";
        RowMapper<Employee>rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        List<Employee>employees = jdbcTemplate.query(sql, rowMapper, 1);
        System.out.println(employees);
    }
    

    获取单个列的值或者做统计查询

    @Test
    public void testQueryForList2(){
        String sql = "select count(id) from employees ";
        long count = jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println(count);
    }
    

    在JDBC模板中使用具名参数

    配置文件

    <bean id="namedParameterJdbcTemplate"
        class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    

    测试类

    @Test
    public void testNamedParameterJdbcTemplate(){
        String sql = "insert into employees(id, last_name, email, dept_id) values(:id, :ln, :email, :deptId) ";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", 5);
        paramMap.put("ln", "Zhang");
        paramMap.put("email", "Zhang0413@test.com");
        paramMap.put("deptId", 1);
        namedParameterJdbcTemplate.update(sql, paramMap);
     }
    

    使用具名参数的优点:
    有多个参数,则不用再去对应配置。直接对应参数名,便于维护。
    使用具名参数的缺点:
    较为麻烦。

    使用具名参数时可以使用update(String sql, SqlParameterSource paramSource)方法进行更新操作。好处是可以通过SqlParameterSource的实现类直接传入一个对象。语句中的参数名要和类的属性一致。使用SqlParameterSource的BeanPropertySqlParameterSource实现类作为参数。

    相关文章

      网友评论

          本文标题:Spring使用JDBCTemplate

          本文链接:https://www.haomeiwen.com/subject/magdyhtx.html