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

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

<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ū)動(dòng) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!--spring jdbc,這個(gè)依賴中有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ù)準(zhǔn)備
首先,我們創(chuàng)建一個(gè)名為 spring6的數(shù)據(jù)庫(kù)
/* 判斷該數(shù)據(jù)庫(kù)是否存在,不存在,創(chuàng)建*/ CREATE DATABASE IF NOT EXISTS spring6;
然后在 spring6 數(shù)據(jù)庫(kù)中創(chuàng)建一個(gè)名為 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);


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

package com.rainbowsea.spring6.bean;
/**
* user 數(shù)據(jù)表對(duì)應(yīng)的映射的 bean 對(duì)象
*/
public class User {
// 定義包裝類,作為屬性類型,防止 數(shù)據(jù)庫(kù)中的數(shù)值為 null,報(bào)錯(cuò)
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 。這個(gè)類上的使用,我們 new 對(duì)象就好了,而Spring 可以幫我們 new 對(duì)象,所以,我們就將這個(gè)new JdbcTemplate 對(duì)象這件事交給 Spring 來(lái)做。直接將這個(gè)類配置到 spring.xml 的配置文件當(dāng)中,納入 Bean管理即可。

我們來(lái)看一下這個(gè)JdbcTemplate源碼:

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

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

@Override
public Connection getConnection() throws SQLException {
try {
// 注冊(cè)驅(qū)動(dòng)
Class<?> clazz = Class.forName(driver);
// 獲取數(shù)據(jù)庫(kù)連接對(duì)象
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 對(duì)象
* 只要實(shí)現(xiàn)了DataSource 接口的都是數(shù)據(jù)源
* 德魯伊連接池,C3p0連接池,dbcp連接池,都實(shí)現(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 {
// 注冊(cè)驅(qū)動(dòng)
Class<?> clazz = Class.forName(driver);
// 獲取數(shù)據(jù)庫(kù)連接對(duì)象
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ù)源,我們需要把這個(gè)數(shù)據(jù)源傳遞給JdbcTemplate。因?yàn)镴dbcTemplate中有一個(gè)DataSource屬性;同時(shí)獲取為該 DataSource 數(shù)據(jù)源,通過(guò)Spring的set 注入,為其中的成員變量賦值。就是連接我們MySQL數(shù)據(jù)庫(kù)的一些信息。如下:

<!-- 配置自己寫的數(shù)據(jù)源-->
<!-- 當(dāng)然,也可以集成其他人或者其他組織開(kāi)發(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í)候,我們就可以將這個(gè)數(shù)據(jù)源傳遞給JdbcTemplate。因?yàn)镴dbcTemplate中有一個(gè)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ù)源-->
<!-- 當(dāng)然,也可以集成其他人或者其他組織開(kāi)發(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)境準(zhǔn)備好了,數(shù)據(jù)表也準(zhǔn)備好了,下面就可以開(kāi)始通過(guò)Spring 的JdbcTemplate 操作數(shù)據(jù)庫(kù)了(對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查)的操作了。具體內(nèi)容如下。
4. 開(kāi)始
4.1 從數(shù)據(jù)表中插入(添加)數(shù)據(jù)
首先,我們通過(guò) Spring 讀取上面我們配置好的spinrg.xml 文件當(dāng)中的,從而實(shí)例化 JdbcTemplate 類對(duì)象。

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

返回值: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對(duì)象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 注意:insert delete update的sql語(yǔ)句,都是執(zhí)行update方法。,? 表示占位符
// 因?yàn)?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當(dāng)中的JdbcTemplate,對(duì)于數(shù)據(jù)庫(kù)上的增刪改,執(zhí)行SQL語(yǔ)句都是使用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對(duì)象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 注意:insert delete update的sql語(yǔ)句,都是執(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當(dāng)中的JdbcTemplate,對(duì)于數(shù)據(jù)庫(kù)上的增刪改,執(zhí)行SQL語(yǔ)句都是使用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對(duì)象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 編寫SQL語(yǔ)句,? 表示占位符
String sql = "delete from user2 where id = ?";
// 執(zhí)行更新操作
// 注意:insert delete update的sql語(yǔ)句,都是執(zhí)行update方法。
// 返回修改的記錄條數(shù)
int count = jdbcTemplate.update(sql, 4);
System.out.println("插入的記錄條數(shù):" + count);
}
}
4.4 從數(shù)據(jù)表中查詢一個(gè)對(duì)象
關(guān)于查詢一條記錄,使用 jdbcTemplate.queryForObject() 方法:

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


第三個(gè)參數(shù):SQL語(yǔ)句當(dāng)中的 ? 占位符??勺冮L(zhǎng)參數(shù),給sql語(yǔ)句的占位符問(wèn)號(hào)傳值。
返回值:運(yùn)用了泛型,也就是對(duì)應(yīng)數(shù)據(jù)庫(kù)表中在Java當(dāng)中相對(duì)應(yīng),映射的 bean 類。

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

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

這里我們查詢,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對(duì)象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
// 執(zhí)行插入操作
// 編寫SQL語(yǔ)句,? 表示占位符
// 執(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ù)
對(duì)于數(shù)據(jù)表中的批量添加數(shù)據(jù),我們這里需要用上:jdbcTemplate.batchUpdate() 方法
- 第一個(gè)參數(shù):String sql 要執(zhí)行的SQL語(yǔ)句
- 第二個(gè)參數(shù): List<Object[]> batchArgs 是一個(gè)List集合當(dāng)中存儲(chǔ) Object[ ] 數(shù)組,注意是數(shù)組,這個(gè)List 就是,我們批量插入數(shù)據(jù)時(shí),對(duì)于SQL語(yǔ)句當(dāng)中的
?占位符的傳值,因?yàn)檫@個(gè)參數(shù)是: List<Object[]> batchArgs,所以我們需要將我們 ?占位符的值,放入到List 集合當(dāng)中,再作為參數(shù),傳給jdbcTemplate.batchUpdate() 方法。

- 返回值:就是你各個(gè)批量插入的記錄的,各個(gè)成功的記錄條數(shù),比如這里我們批量添加了3條記錄,那么如果三條記錄都插入成功了的話,就是[1,1,1]。表示每執(zhí)行一次這個(gè):"insert into user2(real_name,age) values(?,?)"; SQL語(yǔ)句就會(huì)影響到一條記錄。
插入這條記錄,產(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對(duì)象
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 集合當(dāng)中,再作為參數(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語(yǔ)句不同而已。下面我們將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對(duì)象
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 集合當(dāng)中,再作為參數(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語(yǔ)句不同而已。下面我們將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對(duì)象
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 集合當(dāng)中,再作為參數(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ù),可以參與的更加細(xì)節(jié):例如:如果你想寫JDBC代碼,可以使用callback回調(diào)函數(shù)
想要執(zhí)行回調(diào)函數(shù),用使用上 jdbcTemplate.execute() 方法,

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

PreparedStatementCallback,一般我們通常是使用 lambda 表達(dá)式 ,簡(jiǎn)化代碼。


需要注意的是:注冊(cè)回調(diào)函數(shù),當(dāng)execute 方法執(zhí)行的時(shí)候,回調(diào)函數(shù)中的doInPreparedStatement()會(huì)被調(diào)用
返回值:就是這里運(yùn)用的泛型,返回值,就是你傳的 T.class 的 Bean 對(duì)象。
這里我們使用回調(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);
// 準(zhǔn)備 sql語(yǔ)句
String sql = "select id,real_name,age from user2 where id = ?";
// 注冊(cè)回調(diào)函數(shù),當(dāng)execute 方法執(zhí)行的時(shí)候,回調(diào)函數(shù)中的doInPreparedStatement()會(huì)被調(diào)用
User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() {
@Override
public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
User user = null;
// 1 表示第一個(gè)占位符,?的下標(biāo), 為 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ù)源。這里我們其實(shí)也是可以使用別人寫好的。例如比較牛的德魯伊連接池。
第一步:引入德魯伊連接池的依賴。(畢竟是別人寫的,我需要導(dǎo)入,才能使用),使用 maven 導(dǎo)入。

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


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


這里我們用:driverClassName,進(jìn)行簡(jiǎn)單類型的set 注入,對(duì) 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 是 非簡(jiǎn)單類型了,是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>下面,我們測(cè)試,使用德魯伊數(shù)據(jù)庫(kù)連接池,進(jìn)行對(duì)數(shù)據(jù)庫(kù)的查詢:
查詢id 為1的一條記錄。


查詢成功。
我們?cè)偈褂玫卖斠吝M(jìn)行多個(gè)數(shù)據(jù)的查詢。同樣也是沒(méi)有問(wèn)題的。

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

