Spring学习笔记 | Spring中的JdbcTemplate和具名参数

JdbcTempplate

需要传入的jar包:

  • spring-jdbc-5.1.9.RELEASE.jar
  • spring-tx-5.1.9.RELEASE.jar

方法:

  • public int update(String sql, @Nullable Object... args)
    更新操作,第一个参数是sql语句,第二个参数是sql语句中的参数

  • public int[] batchUpdate(String sql, List<Object[]> batchArgs)
    批量更新操作,第一个参数是sql语句,第二个参数是一个Object[]的集合,Object数组存放的就是一条记录的sql参数,Object数组的集合即指n条记录的sql的参数。

  • public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)
    从数据表中获取一条记录,返回的是该记录对应的实体对象,第一个参数是sql语句。
    第二个参数RowMapper指定如何去映射结果集的行(即返回的是什么实体对象),常用的实现类为BeanPropertyRowMapper

  • public <T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args)
    从数据表中查询多条记录,返回的是对应实体对象的集合。
    第一个参数是sql语句。
    第二个参数RowMapper指定如何去映射结果集的行(即返回的是什么实体对象),常用的实现类为BeanPropertyRowMapper
    第三个参数即是sql的参数。

  • public <T> T queryForObject(String sql, Class<T> requiredType)
    从数据表中查询某个字段或进行统计查询
    第二个参数是要返回的字段的类型。

示例:
我们在数据表中有表如下:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for employees
-- ----------------------------
DROP TABLE IF EXISTS `employees`;
CREATE TABLE `employees`  (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `LAST_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `EMAIL` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `DEPT_ID` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`ID`) USING BTREE,
  INDEX `DEPT_ID`(`DEPT_ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

-- ----------------------------
-- Table structure for departments
-- ----------------------------
DROP TABLE IF EXISTS `departments`;
CREATE TABLE `departments`  (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `DEPT_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`ID`) USING BTREE,
  CONSTRAINT `w` FOREIGN KEY (`ID`) REFERENCES `employees` (`DEPT_ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

然后我们定义实体类Employee如下:

package com.spring.jdbc;

public class Employee {
    private Integer id;
    private String lastName;
    private String email;

    private Integer deptId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getDeptId() {
        return deptId;
    }

    public void setDeptId(Integer deptId) {
        this.deptId = deptId;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", deptId=" + deptId +
                '}';
    }
}

定义一个外部资源文件db.properties

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring4

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

定义配置文件applicationContext-jdbc.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>

    <!-- 配置c3p0 -->
    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="initialPoolSize" value="${jdbc.initPoolSize} "/>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
    </bean>

    <!-- 配置Spring的jdbcTemplate -->
    <bean id="jdbcTemplate"
          class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

单元测试类代码如下(每个方法均有测试):

package com.spring.jdbc;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import javax.sql.DataSource;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCTestTest {

    private ApplicationContext ctx = null;
    private JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    {
        ctx = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml");
        jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
    }

    /***
     * 获取单个列的值,或做统计查询
     * 使用queryForObject()
     */
    @Test
    public void testQueryForObject2(){
        String sql = "select count(id) from employees";
        long count = jdbcTemplate.queryForObject(sql,Long.class);
        System.out.println(count);
    }


    /***
     *
     * 查询集合
     * 注意调用的不是queryForList()
     */
    @Test
    public void testQueryForList(){
        String sql = "select id,last_name lastName, email from employees where id > ?";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper <>(Employee.class);
        List<Employee> employees = jdbcTemplate.query(sql,rowMapper,2);

        System.out.println(employees);
    }

    /**
     * 从数据库中获取一条记录,得到一个对象
     * 调用jdbcTemplate.queryForObject(sql,rowMapper,1);方法
     * 其中的RowMapper指定如何去映射结果集的行,常用的实现类为BeanPropertyRowMapper.
     * 使用的sql中列的别名完成列名和类属性名的映射。
     * 但是不支持级联属性(即不能将表中的dept_id赋给department的id属性。)
     */
    @Test
    public void testQueryForObject(){
        String sql = "select id,last_name lastname,email from employees where id = ?";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper <>(Employee.class);
        Employee employees = jdbcTemplate.queryForObject(sql,rowMapper,1);

        System.out.println(employees);
    }


    /***
     * 执行批量更新:INSERT
     * 最后一个参数是Objectp[]的List类型
     */
    @Test
    public void testBatchUpdate(){
        String sql = "insert into employees(last_name,email,dept_id) values(?,?,?)";
        List<Object[]> batchArgs = new ArrayList <>();
        batchArgs.add(new Object[]{"AA","AA@qq.com",1});
        batchArgs.add(new Object[]{"BB","BB@qq.com",1});
        batchArgs.add(new Object[]{"CC","CC@qq.com",1});
        batchArgs.add(new Object[]{"DD","DD@qq.com",1});
        jdbcTemplate.batchUpdate(sql, batchArgs);

    }
    /**
     *  测试更新
     */
    @Test
    public void testUpdate(){
        String sql = "UPDATE employees SET last_name = ? WHERE id =?";
        jdbcTemplate.update(sql,"Sar",1);

    }

}

通过NamedParameterJdbcTemplate在JDBC模板中使用具名参数

我们平时在写sql语句的时候一般都是如这种形式:String sql = "insert into employees(last_name,email,dept_id) values(?,?,?)",对于参数占位符我们是使用?。但是对于有很多参数的时候就显得有点麻烦,而具名参数的含义就是可以给参数占位符取名,即如这种形式:String sql = "insert into employees(last_name,email,dept_id) values(:ln,:email,:deptid)"

在Spring中使用NamedParameterJdbcTemplate在JDBC模板中使用具名参数。
首先我们需要在applicationContext-jdbc.xml配置文件中配置NamedParameterJdbcTemplate,且该类没有无参的构造器,因此必须为其构造器指定参数。

对于使用进行更新时,其update()方法有两种参数可以传:

  • 对于第一种方法,第二个参数要传入 Map<String,Object>类型的,键是参数占位符的名字,值是要写入表的值。这种方法比较麻烦。(具体用法看示例中的testNamedParameterJdbcTemplate()
  • 对于第二种方法,其参数传入一个SqlParameterSource类型的值,而SqlParameterSource可以使用BeanPropertySqlParameterSource初始化并且传入一个已经实例化的实体对象。(具体用法看示例中的testNamedParameterJdbcTemplate2()

配置如下:

  <!-- 
    配置NamedParameterJdbcTemplate,
    该对象可以使用具名参数,其没有无参的构造器,所以必须为其构造器指定参数 
  -->
    <bean id="namedParameterJdbcTemplate"
          class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"/>
    </bean>
package com.spring.jdbc;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import javax.sql.DataSource;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCTestTest {

    private ApplicationContext ctx = null;
    private JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    {
        ctx = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml");
        jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
        namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.class);
    }

     /***
     * 使用具名参数时,可以使用public int update(String sql, SqlParameterSource paramSource)方法进行更新操作
     * 1.SQL语句的参数名和类属性名一致
     * 2.使用SqlParameterSource的BeanPropertySqlParameterSource实现类作为参数,可以直接传入实体类。
     */
    @Test
    public void testNamedParameterJdbcTemplate2(){
        String sql = "insert into employees(last_name,email,dept_id)" +
                " values(:lastName,:email,:deptId)";

        Employee employee = new Employee();
        employee.setLastName("XXX");
        employee.setEmail("XXX@sina.com");
        employee.setDeptId(1);
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(employee);
        namedParameterJdbcTemplate.update(sql,paramSource);
    }

    /***
     * 使用NamedParameterJdbcTemplate可以为参数取名字。
     * 1.好处:若有多个参数,则不用再去对应位置,直接对应参数名,便于维护
     * 2.缺点:较为麻烦。
     */
    @Test
    public void testNamedParameterJdbcTemplate(){
        String sql = "insert into employees(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);
        namedParameterJdbcTemplate.update(sql,paramMap);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值