Spring6?的JdbcTemplate的JDBC模板類的使用介紹(最新推薦)
1. Spring6 的JdbcTemplate的JDBC模板類的詳細使用說明
JdbcTemplate 是Spring 提供的一個JDBC模板類,是對JDBC的封裝,簡化JDBC代碼,當然,你也可以不用,可以讓Spring集成其它的ORM框架,例如:MyBatis,Hibernate 等。
下面我們正式開始對 JdbcTemplate 上的學(xué)習(xí),完成增刪改查。
2. 環(huán)境準備
這里,我們新建一個模塊,方便學(xué)習(xí),如下:因為我們這里是Spring6,而Spring6最低支持的JDK是17,所以我這里是 JDK17的。

新建好模塊以后,我們需要導(dǎo)入相關(guān)的依賴,這里我們通過 maven 導(dǎo)入依賴。
具體的依賴有:
- spring context 依賴 (spring6 的依賴)
- mysql-connector-java(關(guān)于MySQL驅(qū)動的依賴,因為我們要連接數(shù)據(jù)庫,這里我們連接的是MySQL數(shù)據(jù)庫)
- spring-jdbc (spring jdbc,這個依賴中有JdbcTemplate)
- junit (Junit4 單元測試依賴)
特殊的還有這個,也得添加上

<repositories>
<repository>
<id>repository.spring.milestone</id>
<name>Spring Milestone Repository</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rainbowsea</groupId>
<artifactId>spring6-009-jdbc-blog</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<repositories>
<repository>
<id>repository.spring.milestone</id>
<name>Spring Milestone Repository</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<!-- spring context 依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.11</version>
</dependency>
<!-- mysql驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!--spring jdbc,這個依賴中有JdbcTemplate-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.0-M2</version>
</dependency>
<!-- junit4 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>3. 數(shù)據(jù)準備
首先,我們創(chuàng)建一個名為 spring6的數(shù)據(jù)庫
/* 判斷該數(shù)據(jù)庫是否存在,不存在,創(chuàng)建*/ CREATE DATABASE IF NOT EXISTS spring6;
然后在 spring6 數(shù)據(jù)庫中創(chuàng)建一個名為 user 的數(shù)據(jù)表
CREATE TABLE `user` ( `id` int NOT NULL AUTO_INCREMENT, `real_name` varchar(255) , `age` int , PRIMARY KEY (`id`) USING BTREE ) ; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (1, '李四', 33); INSERT INTO `user` VALUES (2, '李華', 20); INSERT INTO `user` VALUES (3, '李華', 21);


準備實體類:表user對應(yīng)的實體類User。根據(jù)user 數(shù)據(jù)表結(jié)構(gòu)創(chuàng)建對于的Bean 實體類。
注意: 這里我們定義用對應(yīng)簡單類型的包裝類,來定義成員變量,防止數(shù)據(jù)庫的數(shù)值為Null時,報錯,中斷。

package com.rainbowsea.spring6.bean;
/**
* user 數(shù)據(jù)表對應(yīng)的映射的 bean 對象
*/
public class User {
// 定義包裝類,作為屬性類型,防止 數(shù)據(jù)庫中的數(shù)值為 null,報錯
private Integer id;
private String realName;
private Integer age;
public User(Integer id, String realName, Integer age) {
this.id = id;
this.realName = realName;
this.age = age;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", realName='" + realName + '\'' +
", age=" + age +
'}';
}
}配置編寫相關(guān)的spring.xml的信息
JdbcTemplate 是Spring 提供好的類,這類的完整類名是:org.springframework.jdbc.core.JdbcTemplate 。這個類上的使用,我們 new 對象就好了,而Spring 可以幫我們 new 對象,所以,我們就將這個new JdbcTemplate 對象這件事交給 Spring 來做。直接將這個類配置到 spring.xml 的配置文件當中,納入 Bean管理即可。

我們來看一下這個JdbcTemplate源碼:

所以這里,我們只需要配置好 DataSource 數(shù)據(jù)源,用來連接數(shù)據(jù)庫即可,將DataSource 屬性進行 set 注入賦值上??梢钥吹絁dbcTemplate中有一個DataSource屬性,這個屬性是數(shù)據(jù)源,我們都知道連接數(shù)據(jù)庫需要Connection對象,而生成Connection對象是數(shù)據(jù)源負責(zé)的。所以我們需要給JdbcTemplate設(shè)置數(shù)據(jù)源屬性。
所有的數(shù)據(jù)源都是要實現(xiàn)javax.sql.DataSource接口的。這個數(shù)據(jù)源可以自己寫一個,也可以用寫好的,比如:阿里巴巴的德魯伊連接池,c3p0,dbcp等。我們這里自己先手寫一個數(shù)據(jù)源。
自己的數(shù)據(jù)源,數(shù)據(jù)源存在的目的是為了提供 Connection 對象;只要實現(xiàn)了DataSource 接口的都是數(shù)據(jù)源:德魯伊連接池,C3p0連接池,dbcp連接池,都實現(xiàn)了DataSource 接口
如下:

重寫其中的**public Connection getConnection() throws SQLException ** 方法,注意是沒有參數(shù)的。

@Override
public Connection getConnection() throws SQLException {
try {
// 注冊驅(qū)動
Class<?> clazz = Class.forName(driver);
// 獲取數(shù)據(jù)庫連接對象
Connection connection = DriverManager.getConnection(url, userName, password);
System.out.println(connection);
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}package com.rainbowsea.spring6.bean;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
/**
* 自己的數(shù)據(jù)源,數(shù)據(jù)源存在的目的是為了提供 Connection 對象
* 只要實現(xiàn)了DataSource 接口的都是數(shù)據(jù)源
* 德魯伊連接池,C3p0連接池,dbcp連接池,都實現(xiàn)了DataSource 接口
*/
public class MyDataSource implements DataSource {
private String driver;
private String url;
private String userName;
private String password;
public MyDataSource() {
}
public MyDataSource(String driver, String url, String userName, String password) {
this.driver = driver;
this.url = url;
this.userName = userName;
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "MyDataSource{" +
"driver='" + driver + '\'' +
", url='" + url + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
@Override
public Connection getConnection() throws SQLException {
try {
// 注冊驅(qū)動
Class<?> clazz = Class.forName(driver);
// 獲取數(shù)據(jù)庫連接對象
Connection connection = DriverManager.getConnection(url, userName, password);
System.out.println(connection);
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}寫完數(shù)據(jù)源,我們需要把這個數(shù)據(jù)源傳遞給JdbcTemplate。因為JdbcTemplate中有一個DataSource屬性;同時獲取為該 DataSource 數(shù)據(jù)源,通過Spring的set 注入,為其中的成員變量賦值。就是連接我們MySQL數(shù)據(jù)庫的一些信息。如下:

<!-- 配置自己寫的數(shù)據(jù)源-->
<!-- 當然,也可以集成其他人或者其他組織開發(fā)的數(shù)據(jù)源,例如:c3p0,dbcp druid-->
<bean id="dataSource" class="com.rainbowsea.spring6.bean.MyDataSource">
<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring6"></property>
<property name="userName" value="root"></property>
<property name="password" value="123"></property>
</bean>這時候,我們就可以將這個數(shù)據(jù)源傳遞給JdbcTemplate。因為JdbcTemplate中有一個DataSource屬性。


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置自己寫的數(shù)據(jù)源-->
<!-- 當然,也可以集成其他人或者其他組織開發(fā)的數(shù)據(jù)源,例如:c3p0,dbcp druid-->
<bean id="dataSource" class="com.rainbowsea.spring6.bean.MyDataSource">
<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring6"></property>
<property name="userName" value="root"></property>
<property name="password" value="123"></property>
</bean>
<!-- 配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>這里,我們的環(huán)境準備好了,數(shù)據(jù)表也準備好了,下面就可以開始通過Spring 的JdbcTemplate 操作數(shù)據(jù)庫了(對數(shù)據(jù)庫進行增刪改查)的操作了。具體內(nèi)容如下。
4. 開始
4.1 從數(shù)據(jù)表中插入(添加)數(shù)據(jù)
首先,我們通過 Spring 讀取上面我們配置好的spinrg.xml 文件當中的,從而實例化 JdbcTemplate 類對象。

然后使用:jdbcTemplate.update() 的方法,執(zhí)行SQL語句。
需要注意的是:在Spring當中的JdbcTemplate,對于數(shù)據(jù)庫上的增刪改,執(zhí)行SQL語句都是使用update() 的方法處理的。
第一個參數(shù):String sql
第二個參數(shù): @Nullable Object... args 是一個可變參數(shù)(是一個數(shù)組),表示
表示:SQL語句當中的? 占位符的要填入的值。

返回值:int 表示修改/更新的記錄條數(shù)。



package com.rainbowsea.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTest {
@Test
public void testInsert() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 注意:insert delete update的sql語句,都是執(zhí)行update方法。,? 表示占位符
// 因為 id 是自增的,所以,這里我們不賦值
String sql = "insert into user(real_name,age) values(?,?)";
// 返回修改的記錄條數(shù)
int count = jdbcTemplate.update(sql, "張三", 30);
System.out.println("插入的記錄條數(shù):" + count);
}
}
4.2 從數(shù)據(jù)表中修改數(shù)據(jù)
在Spring當中的JdbcTemplate,對于數(shù)據(jù)庫上的增刪改,執(zhí)行SQL語句都是使用update() 的方法處理的。
我們這里:將id 為1的,real_name修改為:張小六,age 為 18

package com.rainbowsea.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTest {
@Test
public void testUpdate() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 注意:insert delete update的sql語句,都是執(zhí)行update方法。,? 表示占位符
// 執(zhí)行更新操作
String sql = "update user2 set real_name = ?, age = ? where id = ?";
int count = jdbcTemplate.update(sql, "張小六", 18, 1);
System.out.println(count);
}
}
4.3 從數(shù)據(jù)表中刪除數(shù)據(jù)
在Spring當中的JdbcTemplate,對于數(shù)據(jù)庫上的增刪改,執(zhí)行SQL語句都是使用update() 的方法處理的。
我們這里:將id 為4的一條記錄刪除了。

package com.rainbowsea.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTest {
@Test
public void testDelete() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 編寫SQL語句,? 表示占位符
String sql = "delete from user2 where id = ?";
// 執(zhí)行更新操作
// 注意:insert delete update的sql語句,都是執(zhí)行update方法。
// 返回修改的記錄條數(shù)
int count = jdbcTemplate.update(sql, 4);
System.out.println("插入的記錄條數(shù):" + count);
}
}
4.4 從數(shù)據(jù)表中查詢一個對象
關(guān)于查詢一條記錄,使用 jdbcTemplate.queryForObject() 方法:

第一個參數(shù):String sql 要執(zhí)行的SQL語句
第二個參數(shù):BeanPropertyRowMapper 與對應(yīng)數(shù)據(jù)庫表中 bean 類的相映射的類。一般用: new BeanPropertyRowMapper<>(T.class) 這樣的對象裝配上。Bean屬性值和數(shù)據(jù)庫記錄行的映射對象。在構(gòu)造方法中指定映射的對象類型。


第三個參數(shù):SQL語句當中的 ? 占位符。可變長參數(shù),給sql語句的占位符問號傳值。
返回值:運用了泛型,也就是對應(yīng)數(shù)據(jù)庫表中在Java當中相對應(yīng),映射的 bean 類。

這里我們查詢一個id為1的,其中的ID,real_name,age 的一條記錄

import com.rainbowsea.spring6.bean.User;
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;
public class JdbcTest {
@Test
public void testSelectOne() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 編寫SQL語句,? 表示占位符
String sql = "select id, real_name, age from user2 where id = ?";
// 執(zhí)行更新操作
// 返回對應(yīng)查詢到的 Bean 類
User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 1);
System.out.println(user);
}
}
4.5 從數(shù)據(jù)表中查詢一個值
查詢數(shù)據(jù)表當中有幾條記錄,對應(yīng)查詢數(shù)據(jù)表中的一個值的內(nèi)容,我們同樣還是使用:jdbcTemplate.queryForObject() 方法來進行。不同的是,這個參數(shù)是兩個的,是對應(yīng)的類對象,
- 比如這里我們查詢的是一個數(shù)據(jù)表中有幾條記錄,幾條記錄,就是一個值了,一個數(shù)值類型的類對象了,可以是 int.class,也可以是 long.class,還可以是 short.class 因為只要是數(shù)值類型就可以了。
- 返回值是對應(yīng)類的包裝類,



import com.rainbowsea.spring6.bean.User;
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 java.util.List;
public class JdbcTest {
/**
* 查詢數(shù)據(jù)表中的一個值
*/
@Test
public void testSelectOneValue() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 編寫SQL語句,? 表示占位符
// 執(zhí)行select
String sql = "select count(1) from user2";
// 返回對應(yīng)數(shù)據(jù)類型的包裝類
Integer count = jdbcTemplate.queryForObject(sql, int.class);
System.out.println(count);
}
}
用 Long.class 也是可以的。

4.6 從數(shù)據(jù)表中查詢多條記錄
查詢數(shù)據(jù)表中的多個對象,我們就要使用:jdbcTemplate.query() 方法了
- 第一個參數(shù):同樣還是:要執(zhí)行的SQL語句
- 第二個參數(shù):。Bean屬性值和數(shù)據(jù)庫記錄行的映射對象。在構(gòu)造方法中指定映射的對象類型。;BeanPropertyRowMapper 與對應(yīng)數(shù)據(jù)庫表中 bean 類的相映射的類。一般用: new BeanPropertyRowMapper<>(T.class) 這樣的對象裝配上。
- 返回值:是一個List 集合了,因為我們查詢到的多條記錄,自然就是存儲到集合當中去了。

這里我們查詢,user2 表中的所有用戶的所有信息。

import com.rainbowsea.spring6.bean.User;
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 java.util.List;
public class JdbcTest {
/**
* 查詢多條記錄
*/
@Test
public void testSelectAll() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 編寫SQL語句,? 表示占位符
// 執(zhí)行select
String sql = "select id, real_name, age from user2";
List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
System.out.println(users);
}
}
4.7 從數(shù)據(jù)表中批量添加數(shù)據(jù)
對于數(shù)據(jù)表中的批量添加數(shù)據(jù),我們這里需要用上:jdbcTemplate.batchUpdate() 方法
- 第一個參數(shù):String sql 要執(zhí)行的SQL語句
- 第二個參數(shù): List<Object[]> batchArgs 是一個List集合當中存儲 Object[ ] 數(shù)組,注意是數(shù)組,這個List 就是,我們批量插入數(shù)據(jù)時,對于SQL語句當中的
?占位符的傳值,因為這個參數(shù)是: List<Object[]> batchArgs,所以我們需要將我們 ?占位符的值,放入到List 集合當中,再作為參數(shù),傳給jdbcTemplate.batchUpdate() 方法。

- 返回值:就是你各個批量插入的記錄的,各個成功的記錄條數(shù),比如這里我們批量添加了3條記錄,那么如果三條記錄都插入成功了的話,就是[1,1,1]。表示每執(zhí)行一次這個:"insert into user2(real_name,age) values(?,?)"; SQL語句就會影響到一條記錄。
插入這條記錄,產(chǎn)生了一條記錄的影響。
三條記錄,各自都是只產(chǎn)生了一條記錄的影響



import com.rainbowsea.spring6.bean.User;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JdbcTest {
/**
* 批量添加數(shù)據(jù)
*/
@Test
public void testAddBatch() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 批量添加,id 是自增的,這里可以省略
String sql = "insert into user2(real_name,age) values(?,?)";
Object[] objs1 = {"小花", 20};
Object[] objs2 = {"小明", 21};
Object[] objs3 = {"小剛", 22};
// 將要修改的數(shù)據(jù)封裝到 List 集合當中,再作為參數(shù)傳入
List<Object[]> list = new ArrayList<>();
list.add(objs1);
list.add(objs2);
list.add(objs3);
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println(Arrays.toString(count));
}
}
4.8 從數(shù)據(jù)表中批量修改數(shù)據(jù)
從數(shù)據(jù)表中批量修改數(shù)據(jù)還是使用:jdbcTemplate.batchUpdate() 方法。唯一不同的就是執(zhí)行的SQL語句不同而已。下面我們將id 為 5,6,7 的 age 改為 10,11,12


import com.rainbowsea.spring6.bean.User;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JdbcTest {
/**
* 批量修改
*/
@Test
public void testUpdateBatch() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 批量修改
String sql = "update user2 set age = ? where id = ?";
Object[] objs1 = { 10, 5};
Object[] objs2 = { 11, 6};
Object[] objs3 = { 12, 7};
// 將要修改的數(shù)據(jù)封裝到 List 集合當中,再作為參數(shù)傳入
List<Object[]> list = new ArrayList<>();
list.add(objs1);
list.add(objs2);
list.add(objs3);
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println(Arrays.toString(count));
}
}
4.9 從數(shù)據(jù)表中批量刪除數(shù)據(jù)
從數(shù)據(jù)表中批量刪除數(shù)據(jù)還是使用:jdbcTemplate.batchUpdate() 方法。唯一不同的就是執(zhí)行的SQL語句不同而已。下面我們將user 數(shù)據(jù)表中的 id 為 5,6,7 的記錄刪除了。

import com.rainbowsea.spring6.bean.User;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JdbcTest {
/**
* 批量刪除
*/
@Test
public void testDeleteBatch() {
// 獲取JdbcTemplate對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 批量刪除
String sql = "delete from user2 where id = ?";
Object[] objs1 = {5};
Object[] objs2 = {6};
Object[] objs3 = {7};
// 將要修改的數(shù)據(jù)封裝到 List 集合當中,再作為參數(shù)傳入
List<Object[]> list = new ArrayList<>();
list.add(objs1);
list.add(objs2);
list.add(objs3);
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println(Arrays.toString(count));
}
}
4.10 JdbcTemplate 使用回調(diào)函數(shù)
使用回調(diào)函數(shù),可以參與的更加細節(jié):例如:如果你想寫JDBC代碼,可以使用callback回調(diào)函數(shù)
想要執(zhí)行回調(diào)函數(shù),用使用上 jdbcTemplate.execute() 方法,

第一個參數(shù)是:String sql 要執(zhí)行的SQL語句第二個參數(shù)是:PreparedStatementCallback action ,是個接口,我們要傳其實例化對象,

PreparedStatementCallback,一般我們通常是使用 lambda 表達式 ,簡化代碼。


需要注意的是:注冊回調(diào)函數(shù),當execute 方法執(zhí)行的時候,回調(diào)函數(shù)中的doInPreparedStatement()會被調(diào)用
返回值:就是這里運用的泛型,返回值,就是你傳的 T.class 的 Bean 對象。
這里我們使用回調(diào)函數(shù),查詢 user 數(shù)據(jù)表中 id 為 2的 用戶的,id, real_name,age 的記錄信息

import com.rainbowsea.spring6.bean.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JdbcTest {
/**
* 回調(diào)函數(shù)
* 如果你想寫JDBC代碼,可以使用callback回調(diào)函數(shù)
*/
@Test
public void testCallback() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 準備 sql語句
String sql = "select id,real_name,age from user2 where id = ?";
// 注冊回調(diào)函數(shù),當execute 方法執(zhí)行的時候,回調(diào)函數(shù)中的doInPreparedStatement()會被調(diào)用
User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() {
@Override
public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
User user = null;
// 1 表示第一個占位符,?的下標, 為 2
ps.setInt(1,2);
ResultSet resultSet = ps.executeQuery();
if(resultSet.next()) {
int id = resultSet.getInt("id");
String realName = resultSet.getString("real_name");
int age = resultSet.getInt("age");
user = new User(id,realName,age);
}
return user;
}
});
System.out.println(user);
}
}
4.11 JdbcTemplate 配合使用上德魯伊連接池
上面演示的是用我們自己寫的數(shù)據(jù)源。這里我們其實也是可以使用別人寫好的。例如比較牛的德魯伊連接池。
第一步:引入德魯伊連接池的依賴。(畢竟是別人寫的,我需要導(dǎo)入,才能使用),使用 maven 導(dǎo)入。

<!--引入德魯伊連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>第二步:將德魯伊中的數(shù)據(jù)源配置到 spring.xml 配置文件中。和配置我們自己寫的一樣。就是一些:對應(yīng)數(shù)據(jù)庫的注冊驅(qū)動,指明數(shù)據(jù)庫的所在位置,以及連接數(shù)據(jù)庫的賬號和密碼。
需要特別注意的是:注意這里是:driverClassName,是簡單類型進行set注入對屬性賦值,簡單類型可以用 value


而如果是使用:driver,用 ref了


這里我們用:driverClassName,進行簡單類型的set 注入,對 this.driver 成員變量的屬性賦值。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 引入德魯伊連接池-->
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 注意這里是:driverClassName,,如果是 driver 是 非簡單類型了,是Driver 類型-->
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring6"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
<!-- 配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="druidDataSource"></property>
</bean>
</beans>下面,我們測試,使用德魯伊數(shù)據(jù)庫連接池,進行對數(shù)據(jù)庫的查詢:
查詢id 為1的一條記錄。


查詢成功。
我們再使用德魯伊進行多個數(shù)據(jù)的查詢。同樣也是沒有問題的。

5. 總結(jié):
- JdbcTemplate 是Spring 提供的一個JDBC模板類,是對JDBC的封裝,簡化JDBC代碼,當然,你也可以不用,可以讓Spring集成其它的ORM框架,例如:MyBatis,Hibernate 等。
- 使用JdbcTemplate 需要導(dǎo)入的如下 jar依賴
spring context 依賴 (spring6 的依賴) mysql-connector-java(關(guān)于MySQL驅(qū)動的依賴,因為我們要連接數(shù)據(jù)庫,這里我們連接的是MySQL數(shù)據(jù)庫) spring-jdbc (spring jdbc,這個依賴中有JdbcTemplate) junit (Junit4 單元測試依賴)
- 在Spring當中的JdbcTemplate,對于數(shù)據(jù)庫上的增刪改,執(zhí)行SQL語句都是使用
update()的方法處理的。 - 關(guān)于查詢一條記錄,使用 jdbcTemplate.queryForObject() 方法:
- 查詢數(shù)據(jù)表中的多個對象,我們就要使用:jdbcTemplate.query() 方法了
- 查詢數(shù)據(jù)表當中有幾條記錄,對應(yīng)查詢數(shù)據(jù)表中的一個值的內(nèi)容,我們同樣還是使用:jdbcTemplate.queryForObject() 方法來進行。不同的是,這個參數(shù)是兩個的,是對應(yīng)的類對象。需要注意的第二個參數(shù),使用的是:對應(yīng)返回類型的 T.class 類
- 使用回調(diào)函數(shù),可以參與的更加細節(jié):例如:如果你想寫JDBC代碼,可以使用callback回調(diào)函數(shù)
- 想要執(zhí)行回調(diào)函數(shù),用使用上 jdbcTemplate.execute() 方法, 需要注意的是:注冊回調(diào)函數(shù),當execute 方法執(zhí)行的時候,回調(diào)函數(shù)中的doInPreparedStatement()會被調(diào)用
- 對于數(shù)據(jù)表中的批量添加刪除修改數(shù)據(jù),我們這里需要用上:jdbcTemplate.batchUpdate() 方法
6. 最后:
到此這篇關(guān)于Spring6 的JdbcTemplate的JDBC模板類的詳細使用說明的文章就介紹到這了,更多相關(guān)Spring6 JdbcTemplate的JDBC模板類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot整合itext實現(xiàn)PDF文件合并
這篇文章主要為大家詳細介紹了Springboot整合itext實現(xiàn)PDF文件合并以及識別圖片轉(zhuǎn)成PDF拼接的相關(guān)知識,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
Java實現(xiàn)AOP功能的封裝與配置的小框架實例代碼
這篇文章主要介紹了Java實現(xiàn)AOP功能的封裝與配置的小框架實例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02
SpringCloud遠程服務(wù)調(diào)用實戰(zhàn)筆記
本文給大家介紹SpringCloud遠程服務(wù)調(diào)用實戰(zhàn)筆記,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-11-11

