【框架】Spring JdbcTemplate

669 阅读1分钟

1 介绍

  JdbcTemplate主要提供5种方法

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL(数据库模式定义语言,如创建数据库:CREATE DATABASE、创建表:CREATE TABLE)语句;
  • update方法:update方法用于执行新增、修改、删除等语句;
  • batchUpdate方法:batchUpdate方法用于执行批处理相关语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法:用于执行存储过程、函数相关语句。

2 案例

1、创建表t_user

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
​
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(0) NOT NULL,
  `name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `age` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
​
SET FOREIGN_KEY_CHECKS = 1;

2、添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.0.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.2.0.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.18</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

3、创建两个配置文件:db.properties和applicationContext.xml

db.properties

jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://192.168.18.132:3306/test?serverTimezone=GMT%2B8&useSSL=false&useAffectedRows=true&allowPublicKeyRetrieval=trueinitPoolSize=5
maxPoolSize=10

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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!--读取配置文件-->
    <context:property-placeholder location="classpath:db.properties" />
    <!--配置c3p0数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
​
        <property name="initialPoolSize" value="${initPoolSize}"/>
        <property name="maxPoolSize" value="${maxPoolSize}"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

4、创建实体类User

public class User {
    private Integer id;
    private String name;
    private Integer age;
    // getset方法,以及toString()方法...
}

5、测试类

public class JdbcTest {
    private ApplicationContext context = null;
    private JdbcTemplate jdbcTemplate = null;
    {
        context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
    }
​
    /**
     * 添加语句
     */
    @Test
    public void testInsert() {
        String sql = "insert into t_user(id, name, age) values(?, ?, ?)";
        jdbcTemplate.update(sql, 1, "小明", 20);
    }
​
    /**
     * 更新语句
     */
    @Test
    public void testUpdate() {
        String sql = "update t_user set age = ? where id = ?";
        jdbcTemplate.update(sql, 25, 1);
    }
​
    /**
     * 删除语句
     */
    @Test
    public void testDelete() {
        String sql = "delete from t_user where id = ?";
        jdbcTemplate.update(sql, 1);
    }
​
    /**
     * 批量添加
     */
    @Test
    public void testBatchUpdate() {
        String sql = "insert into t_user(name, age) values(?, ?)";
        // 使用Object[]来表示一个对象
        List<Object[]> userList = new ArrayList<>();
        userList.add(new Object[]{"张三", 16});
        userList.add(new Object[]{"李四", 17});
        userList.add(new Object[]{"王五", 18});
        jdbcTemplate.batchUpdate(sql, userList);
    }
​
    /**
     * 查询一条记录
     */
    @Test
    public void testQueryForObject() {
        // 查询时可使用别名来对应数据库字段
        String sql = "select id, name, age from t_user where id = ?";
        // 使用RowMapper来建立映射关系
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        User user = jdbcTemplate.queryForObject(sql, rowMapper, 2);
        System.out.println(user);
    }
​
    /**
     * 批量查询
     */
    @Test
    public void testQueryForList() {
        String sql = "select id, name, age from t_user";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        List<User> userList = jdbcTemplate.query(sql, rowMapper);
        if (userList.size() > 0) {
            userList.forEach(System.out::println);
        }
    }
​
    /**
     * 获取单个列的值或做统计查询
     * 使用 queryForObject(String sql, Class<Long> requiredType)
     */
    @Test
    public void testQueryForCount() {
        String sql = "select count(id) from t_user";
        System.out.println(jdbcTemplate.queryForObject(sql, Long.class));
    }
}