Java

Spring学习笔记 | Spring中的JdbcTemplat

2019-10-18  本文已影响0人  一颗白菜_

JdbcTempplate

需要传入的jar包:

方法:

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

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()方法有两种参数可以传:

配置如下:

  <!-- 
    配置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);
    }
}
上一篇下一篇

猜你喜欢

热点阅读