0%

【Spring】JdbcTemplate使用

Spring整合的JDBC技术的工具JdbcTemplate使用


1 JdbcTemplate

1.1 介绍

  • JdbcTemplate是Spring对之前学习的Jdbc技术的封装,使得对数据库的操作更加的便捷

1.2 搭建JdbcTemplate

  • (1)引入依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!-- JdbcTemplate -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.6</version>
    </dependency>

    <!-- mysql驱动 -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
    </dependency>
  • (2)创建JdbcTemplate

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public  JdbcTemplate getJdbTemplate() {
    //创建数据源
    DriverManagerDataSource dataSource=new DriverManagerDataSource();
    dataSource.setUsername("root");
    dataSource.setPassword("123");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true");
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

    //通过数据源创建JdbcTemplate
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    return jdbcTemplate;
    }
  • 以上是简单创建,如果与Spring项目整合,可以将JdbcTemplate注入IOC容器中,通过注解使用

1.3 常用JdbcTemplate方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 1. 增、删、改
public int update(final String sql)
public int update(final String sql, Object... args);


// 2. 批量增、删、改
public int[] batchUpdate(String sql, List<Object[]> batchArgs)


// 3. 查询
// 查询-返回基本数据类型
public <T> T queryForObject(String sql, Class<T> requiredType)

// 查询-返回对象
public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)

// 查询-返回列表
public <T> List<T> query(String sql, RowMapper<T> rowMapper)


// 4. SQL通用执行(一般用于DDL:create alter drop)
public void execute(final String sql)

1.4 使用演示

  • (1)数据库表和Bean准备
1
2
3
4
5
6
7
# 建表语句
CREATE TABLE `person` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '唯一标识',
`name` varchar(5) DEFAULT NULL COMMENT '姓名',
`sex` varchar(2) DEFAULT NULL COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
1
2
3
4
5
6
7
8
9
//对应存储Bean
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private Integer id;
private String name;
private String sex;
}
  • (2)增删改
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
//增
public int addPerson() {
JdbcTemplate jdbTemplate = getJdbTemplate();

Person person = new Person(1, "C酱", "女"); //如果主键自增,id可以设置为null
String sql = "insert into person values(?, ?, ?)";
return jdbTemplate.update(sql, person.getId(), person.getName(), person.getSex());
}


//改
public int updatePerson() {
JdbcTemplate jdbTemplate = getJdbTemplate();

Person person = new Person(1, "asaki", "女");
String sql = "update person set name=?, sex=? where id=?";
return jdbTemplate.update(sql, person.getName(), person.getSex(), person.getId());
}


//删
public int deletePerson() {
JdbcTemplate jdbTemplate = getJdbTemplate();

String sql = "delete from person where id=?";
return jdbTemplate.update(sql, "1");
}
  • (3)批量增、删、改
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
//批量增
public int[] addPersons() {
Object[] person1 = new Object[]{1, "C酱", "女"};
Object[] person2 = new Object[]{2, "asaki", "女"};

List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(person1);
batchArgs.add(person2);

String sql = "insert into person values(?, ?, ?)";
return getJdbTemplate().batchUpdate(sql, batchArgs);
}


//批量改
public int[] updatePersons() {
Object[] person1 = new Object[]{"咕料", "男", 1}; //注意顺序
Object[] person2 = new Object[]{"yjj", "男", 2};

List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(person1);
batchArgs.add(person2);

String sql = "update person set name=?, sex=? where id=?";
return getJdbTemplate().batchUpdate(sql, batchArgs);
}


//批量删
public int[] deletePersons() {
Object[] a = new Object[]{1};
Object[] b = new Object[]{2};

List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(a);
batchArgs.add(b);

String sql = "delete from person where id=?";
return getJdbTemplate().batchUpdate(sql, batchArgs);
}
  • (4)查询演示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//查询-返回基本数据类型
public void queryPersonNumber() {
String sql = "select count(*) from person";
Integer num = getJdbTemplate().queryForObject(sql, Integer.class);
System.out.println(num);
}


//查询-返回对象
public void queryPersonById() {
String sql = "select * from person where id = ?";
Person person = getJdbTemplate().queryForObject(sql, new BeanPropertyRowMapper<>(Person.class), 1);
System.out.println(person);
}


//查询-返回列表
public void queryPersons() {
String sql = "select * from person";
List<Person> persons = getJdbTemplate().query(sql, new BeanPropertyRowMapper<>(Person.class));
for(Person person : persons) {
System.out.println(person);
}
}
  • (5)Execute演示
1
2
3
4
5
//execute使用
public void executeTest() {
String sql = "create table Test (id int primary key auto_increment, name varchar(8) not null, age int not null)";
getJdbTemplate().execute(sql);
}