目录

JdbcTemplate

概述

JdbcTemplate是Spring 框架对 JDBC 的封装,使用 JdbcTemplate 可以方便地操作数据库

准备工作

引入相关依赖

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!--操作数据库相关jar-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
</dependency>
<!--Spring-tx提供了非常灵活的事务管理抽象-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
</dependency>
<!-- mysql驱动包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

配置文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <context:property-placeholder location="classpath:db.properties"/>

    <context:component-scan base-package="com.eh.eden.spring.demo" use-default-filters="false">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Service"/>
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>


    <!--step1: 配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
    </bean>

    <!--step2: 引入jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>


</beans>

用法演示

相关测试类

Emp.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.eh.eden.spring.demo.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Emp {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    private Integer deptId;
}

EmpDao.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.eh.eden.spring.demo.dao;

import com.eh.eden.spring.demo.bean.Emp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;

@Repository
public class EmpDao {
    private static final Logger logger = LoggerFactory.getLogger(EmpDao.class);


    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Integer add(Emp emp) {
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        String sql = "insert into tbl_employee(last_name, gender, email,dept_id) values(?,?,?,?)";
        int count = jdbcTemplate.update(con -> {
            PreparedStatement psst = con.prepareStatement(sql, new String[]{"id"});
            psst.setString(1, emp.getLastName());
            psst.setString(2, emp.getGender());
            psst.setString(3, emp.getEmail());
            psst.setInt(4, emp.getDeptId());
            return psst;
        }, keyHolder);
        logger.info("========>添加count: {}", count);
        if (count == 1) {
            return keyHolder.getKey().intValue();
        } else {
            return null;
        }
    }

    public void delete(Integer id) {
        String sql = "delete from tbl_employee where id=?";
        int count = jdbcTemplate.update(sql, id);
        logger.info("========>删除count: {}", count);
    }

    public void updateEmailById(Integer id, String email) {
        String sql = "update tbl_employee set email=? where id =?";
        Object[] args = {email, id};
        int count = jdbcTemplate.update(sql, args);
        logger.info("========>更新count: {}", count);
    }

    public void select(Integer id) {
        String sql = "select * from tbl_employee where id=?";
        Emp emp = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Emp.class), id);
        logger.info("========>查询结果: {}", emp);
    }
}

EmpService.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.eh.eden.spring.demo.service;

import com.eh.eden.spring.demo.bean.Emp;
import com.eh.eden.spring.demo.dao.EmpDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;


@Service
public class EmpService {
    private static final Logger logger = LoggerFactory.getLogger(EmpService.class);

    @Autowired
    private EmpDao empDao;

    // 增
    public Integer add(Emp emp) {
        return empDao.add(emp);
    }

    // 删
    public void delete(Integer id) {
        empDao.delete(id);
    }

    // 改
    public void updateEmailById(Integer id, String email) {
        empDao.updateEmailById(id, email);
    }

    // 查
    public void select(Integer id) {
        empDao.select(id);
    }


    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        EmpService empService = context.getBean("empService", EmpService.class);

        // 增
        Integer id = empService.add(new Emp(null, "燕青", "1", "yq@gmail.com", 2));
        if (id == null) {
            logger.info("测试有误");
        }
        // 查
        empService.select(id);
        // 改
        empService.updateEmailById(id, "高衙内@gmail.com");
        // 删
        empService.delete(id);

    }
}

运行结果:

1
2
3
4
5
20201013 02:12:07 [main] INFO  com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
20201013 02:12:07 [main] INFO  com.eh.eden.spring.demo.dao.EmpDao - ========>添加count: 1
20201013 02:12:07 [main] INFO  com.eh.eden.spring.demo.dao.EmpDao - ========>查询结果: Emp(id=20019, lastName=燕青, gender=1, email=yq@gmail.com, deptId=2)
20201013 02:12:07 [main] INFO  com.eh.eden.spring.demo.dao.EmpDao - ========>更新count: 1
20201013 02:12:07 [main] INFO  com.eh.eden.spring.demo.dao.EmpDao - ========>删除count: 1

说明

查询返回某个值

1
 Integer count = jdbcTemplate.queryForObject(sql, Integer.class);

查询返回对象

1
2
3
4
5
6
7
/*
queryForObject方法中:
		第一个参数:sql语句
		第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面 实现类 完成数据封装
		第三个参数:sql 语句值
*/
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);

查询返回集合

1
List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));

批量操作

批量添加

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
//批量添加
@Override
public void batchAddBook(List<Object[]> batchArgs) {
 String sql = "insert into t_book values(?,?,?)";
//batchUpdate方法 第一个参数:sql语句		第二个参数:List集合,添加多条记录数据
 int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
 System.out.println(Arrays.toString(ints));
}

//批量添加测试
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3","java","a"};
Object[] o2 = {"4","c++","b"};
Object[] o3 = {"5","MySQL","c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用批量添加
bookService.batchAdd(batchArgs);

批量修改

1
2
3
4
5
6
7
//批量修改(同批量添加一样,调用同一个方法)
@Override
public void batchUpdateBook(List<Object[]> batchArgs) {
 String sql = "update t_book set username=?,ustatus=? where user_id=?";
 int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
 System.out.println(Arrays.toString(ints));
}

批量删除