Spring 數據庫編程

Spring JDBC

傳統的JDBC在操作數據庫時,需要先打開數據庫連接,執行SQL語句,然后封裝結果,最后關閉數據庫連接等資源。頻繁的數據庫操作會產生大量的重復代碼,造成代碼冗余,Spring的JDBC模塊負責數據庫資源管理和錯誤處理,大大簡化了開發人員對數據庫的操作,使開發人員可以從頻繁的數據庫操作中解脫出來,從而將更多的精力投入編寫業務邏輯中。

JdbcTemplate

針對數據庫操作,Spring框架提供了JdbcTemplate類,JdbcTemplate是一個模板類,Spring JDBC中的更高層次的抽象類均在JdbcTemplate模板類的基礎上創建。

JdbcTemplate類提供了操作數據庫的基本方法,包括添加、刪除、查詢和更新。在操作數據庫時,JdbcTemplate類簡化了傳統JDBC中的復雜步驟,這可以讓開發人員將更多精力投入到業務邏輯中。

JdbcTemplate類繼承自抽象類JdbcAccessor,同時實現了JdbcTemplate接口。抽象類JdbcAccessor提供了一些訪問數據庫時使用的公共屬性,具體如下:

  • DataSource:DataSource主要功能是獲取數據庫連接。在具體的數據操作中,它還提供對數據庫連接的緩沖池和分布式事務的支持。
  • SQLExceptionTranslator:SQLExceptionTranslator是一個接口,它負責對SQLException異常進行轉譯工作。
Spring JDBC的配置

Spring JDBC中的4個包說明:

包名說明
core(核心包)包含了JDBC的核心功能,包括JdbcTemplate類、SimpleJdbcInsert類、SimpleJdbcCall類以及NamedParameterJdbcTemplate類。
dataSource(數據源包)包含訪問數據源的實用工具類,它有多種數據源的實現,可以在Java EE容器外部測試JDBC代碼。
object(對象包)以面向對象的方式訪問數據庫,它可以執行查詢、修改和更新操作并將返回結果作為業務對象,并且在數據表的列和業務對象的屬性之間映射查詢結果。
support(支持包)包含了core和object包的支持類,如提供異常轉換功能的SQLException類。

Spring對數據庫的操作都封裝在了core、dataSource、object和support這4個包中,想要使用Spring JDBC,就需要對這些包進行配置。在Spring中,JDBC的配置是在配置文件applicationContext.xml中完成的。

配置數據源:包括數據庫驅動??、連接數據庫url??、連接數據庫用戶名??、連接數據庫密碼??。

<bean id="dataSource" class=
"org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- 數據庫驅動 --><property name="driverClassName" value="com.mysql.jdbc.Driver"/><!-- 連接數據庫url --><property name="url" value="jdbc:mysql://localhost:3306/spring"/><property name="username" value="root"/><!-- 連接數據庫用戶名 --><property name="password" value="root"/><!-- 連接數據庫密碼 -->
</bean>

配置JDBC模板:必須使用默認數據源。

<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><!-- 默認必須使用數據源 --><property name="dataSource" ref="dataSource"/>
</bean>

配置注入類

<bean id="xxx" class="Xxx"><property name="JdbcTemplate" ref="JdbcTemplate"/>
</bean>

dataSource配置的4個屬性:

屬性名含義
driverClassName所使用的驅動名稱,對應驅動JAR包中的Driver類
url數據源地址
username訪問數據庫的用戶名
password訪問數據庫的密碼
dataSource屬性值的設定要求

在dataSource的4個屬性中,需要根據數據庫類型或者系統配置設置相應的屬性值。例如,如果數據庫類型不同,需要更改驅動名稱;如果數據庫不在本地,則需要將地址中的localhost替換成相應的主機IP;默認情況下,數據庫端口號可以省略,但如果修改過MySQL數據庫的端口號,則需要加上修改后的端口號。此外,連接數據庫的用戶名和密碼需要與數據庫創建時設置的用戶名和密碼保持一致。

接下來,我們通過JDBCTemplate的實現數據庫的增刪改查操作

首先實現數據庫的配置如下

 <!-- 數據源 --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url"value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"/><property name="username" value="root"/><property name="password" value="root"/></bean><!-- 配置jdbc模板 JdbcTemplate --><bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><!-- 配置注入類 --><bean id="user" class="com.lq.entities.User"><property name="JdbcTemplate" ref="JdbcTemplate"/></bean>

創建項目,目錄如下:

?

在pom文件里添加maven依賴,我們特意引入了spring-jdbc和mysql-connector-java依賴,為了實現jdbc操作。

        <dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>6.1.16</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>6.1.16</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>6.1.16</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.1.16</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-expression</artifactId><version>6.1.16</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.1</version><scope>test</scope></dependency><!--        jdbc包依賴--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.7</version></dependency><!--    事務管理依賴--><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.3.7</version></dependency><!--   數據庫驅動依賴--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.25</version></dependency>

創建實體類Account

package com.lq.entities;/*** @Author: Luqing Teacher* @CreateTime: 2025-02-27* @Description: Account* @Version: 1.0*/public class Account {private int id;private String username;private Double balance;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Double getBalance() {return balance;}public void setBalance(Double balance) {this.balance = balance;}@Overridepublic String toString() {return "Account{" +"id=" + id +", username='" + username + '\'' +", balance=" + balance +'}';}
}

創建接口AccountDao?

package com.lq.dao;import com.lq.entities.Account;import java.util.List;/*** @Author: lzq* @CreateTime: 2025-02-27* @Description: AccountDao* @Version: 1.0*/public interface AccountDao {public int addAccount(Account account);public int updateAccount(Account account);public int deleteAccount(int id);public Account findAccountById(int id);public List<Account> findAllAccount();
}

增刪改查的接口實現:

package com.lq.dao.impl;import com.lq.dao.AccountDao;
import com.lq.entities.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;import java.util.List;/*** @Author: Luqing Teacher* @CreateTime: 2025-02-27* @Description: 實現類* @Version: 1.0*/public class AccountDaoImpl implements AccountDao {private JdbcTemplate jdbcTemplate;public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}@Overridepublic int addAccount(Account acc) {String sql =  "INSERT INTO account (username, balance) VALUES (?, ?)";Object[] obj = new Object[]{acc.getUsername(),acc.getBalance()};int result = this.jdbcTemplate.update(sql, obj);return result;}@Overridepublic int updateAccount(Account account) {String sql = "update account set username=?,balance=? where id=?";Object[] obj = new Object[]{account.getUsername(),account.getBalance(),account.getId()};int result = jdbcTemplate.update(sql, obj);return result;}@Overridepublic int deleteAccount(int id) {String sql = "delete from account where id=?";int result = jdbcTemplate.update(sql, id);return result;}@Overridepublic Account findAccountById(int id) {String sql = "select * from account where id=?";//創建一個新的BeanPropertyRowMapper對象RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);//將id綁定到sql中,并且將查詢結果封裝到Account對象中Account account = this.jdbcTemplate.queryForObject(sql, rowMapper, id);return account;}@Overridepublic List<Account> findAllAccount() {String sql = "select * from account";RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);List<Account> accounts = this.jdbcTemplate.query(sql, rowMapper);return accounts;}
}

本案例的Spring配置文件如下:

<?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="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/><property name="url"value="jdbc:mysql://localhost:3306/springjdbc?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"/><property name="username" value="root"/><property name="password" value="root"/></bean><!-- 配置jdbc模板 JdbcTemplate --><bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><bean id="accountDao" class="com.lq.dao.impl.AccountDaoImpl"><property name="jdbcTemplate" ref="JdbcTemplate"/></bean></beans>

接下來進行測試

package com.lq.test;import com.lq.dao.AccountDao;
import com.lq.entities.Account;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;import java.lang.annotation.Target;
import java.util.List;/*** @Author: Luqing Teacher* @CreateTime: 2025-02-27* @Description: jdbcTest* @Version: 1.0*/public class JdbcTest {@Testpublic void test1(){ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");JdbcTemplate jdbcTemplate = (JdbcTemplate) app.getBean("JdbcTemplate");jdbcTemplate.execute("" +"create table account("+ "id int primary key auto_increment,"+"username varchar(50),"+"balance double)");System.out.println("創建成功");}@Testpublic void test2(){ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");AccountDao accountDao = (AccountDao) app.getBean("accountDao");Account account =  new Account();account.setUsername("肖炎");account.setBalance(1000.0);int res = accountDao.addAccount(account);if(res>0){System.out.println("成功添加了"+res+"條數據");}else{System.out.println("添加失敗");}}@Testpublic void test3(){ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");AccountDao accountDao = (AccountDao) app.getBean("accountDao");Account account =  new Account();account.setId(1);account.setUsername("小醫仙");account.setBalance(1500.0);int res = accountDao.updateAccount(account);if(res>0){System.out.println("成功修改了"+res+"條數據");}else{System.out.println("修改失敗");}}@Testpublic void test4(){ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");AccountDao accountDao = (AccountDao) app.getBean("accountDao");int res = accountDao.deleteAccount(1);if(res>0){System.out.println("成功刪除了"+res+"條數據");}else{System.out.println("刪除失敗");}}@Testpublic void test5(){ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");AccountDao accountDao = (AccountDao) app.getBean("accountDao");Account account = accountDao.findAccountById(2);System.out.println(account);System.out.println("------------------------");List<Account> allAccount = accountDao.findAllAccount();for (Account account1 : allAccount) {System.out.println(account1);}}
}
JdbcTemplate類中常用的查詢方法
方法說明
List query(Stringsql,RowMapper rowMapper)執行String類型參數提供的SQL語句,并通過參數rowMapper返回一個List類型的結果。
List query(Stringsql, PreparedStatementSetter pss, RowMapper rowMapper)根據String類型參數提供的SQL語句創建PreparedStatement對象,通過參數rowMapper將結果返回到List中。
List query(Stringsql, Object[]args, RowMapper rowMapper)使用Object[]的值來設置SQL語句中的參數值,rowMapper是個回調方法,直接返回List類型的數據。
queryForObject(Stringsql, RowMapper rowMapper, Object…args)將args參數綁定到SQL語句中,并通過參數rowMapper返回一個Object類型的單行記錄。
queryForList(Stringsql,Object[]args, class<T>elementType)該方法可以返回多行數據的結果,但必須返回列表,args參數是sql語句中的參數,elementType參數返回的是List數據類型。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/79534.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/79534.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/79534.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

492Q 型氣缸蓋雙端面銑削組合銑床總體設計

一、引言 492Q 型氣缸蓋是發動機的重要組成部分&#xff0c;其雙端面的加工精度對發動機的性能和可靠性有著重要影響。設計一款適用于 492Q 型氣缸蓋雙端面銑削的組合銑床&#xff0c;能夠提高加工效率和質量&#xff0c;滿足發動機生產的需求。 二、總體設計要求 加工精度&…

顎式破碎機的設計

一、引言 顎式破碎機作為礦山、建材等行業的重要破碎設備&#xff0c;其性能優劣直接影響物料破碎效率與質量。隨著工業生產規模的擴大和對破碎效率要求的提高&#xff0c;設計一款高效、穩定、節能的顎式破碎機具有重要意義。 二、設計需求分析 處理能力&#xff1a;根據目…

第三階段面試題

Nginx nginx常用模塊以及其功能 proxy模塊&#xff0c;進行代理功能 ssl模塊&#xff0c;進行HTTPS協議的使用 gzip模塊&#xff0c;進行傳輸數據的壓縮 upstream模塊&#xff0c;進行反向代理時使用 static模塊&#xff0c;靜態資源進行訪問的模塊 cache模塊&#xff0…

鴻蒙NEXT開發鍵盤工具類(ArkTs)

export declare type KeyboardCallBack (show: boolean, height: number) > void; import { AppUtil } from ./AppUtil; import { LogUtil } from ./LogUtil; import { ArrayUtil } from ./ArrayUtil;/*** 鍵盤工具類* author 鴻蒙布道師* since 2025/04/18*/ export class…

基于 LabVIEW 的電液伺服閥測試臺開發

開發了一種基于 LabVIEW 圖形編程語言的自動測試系統&#xff0c;能夠完成電液伺服閥的空載流量特性、壓力增益特性、內泄漏特性等靜態特性的自動測試。針對測試過程中干擾信號頻段與正常信號頻段接近&#xff0c;普通數字濾波器濾波效果不佳的問題&#xff0c;采用迭代濾波分解…

【uniapp】vue2 使用 Vuex 狀態管理

創建store文件夾&#xff1a;store/index.js // index.js import Vue from vue import Vuex from vuex import address from ./modules/address.jsVue.use(Vuex)const store new Vuex.Store({modules: {address} })export default store 創建modules文件夾&#xff1a;modul…

c# 簡單實現將Message的內容保存到txt中,超過100個則清理舊文件

using System; using System.IO; using System.Threading;public static class LogManager {private static readonly object _fileLock new object(); // 線程安全鎖private const int MaxFiles 100; // 最大文件數限制private const string LogDire…

阿里云鏡像加速僅支持阿里云產品了

最近在拉取docker鏡像時一直報超時的錯誤&#xff1a; docker pull hello-world Using default tag: latest Error response from daemon: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exce…

從零實現Git安裝、使用

一、git安裝 Git官方下載 1.下載exe程序 2.雙擊安裝&#xff0c;一直點擊next&#xff0c;默認安裝 安裝完成后&#xff0c;在任意文件夾右鍵&#xff0c;出現下圖所示&#xff0c;即為安裝成功。 3.【Git Bash Here】調出命令窗口&#xff0c;設置用戶名和 email 地址。 gi…

生產環境中如何使用Caffeine+Redis實現二級緩存(詳細分析了遇到的各種情況)

生產環境中如何使用CaffeineRedis實現二級緩存&#xff08;詳細分析了各種情況&#xff09; 本篇主要講解的是實現CaffeineRedis實現一個現成的使用流程。下一篇講解什么是Caffeine以及caffeine的使用 00背景&#xff1a; 使用Caffeine和Redis的二級緩存方案源自于分布式系統…

RT-Thread開發文檔合集

瑞薩VisionBoard開發實踐指南 RT-Thread 文檔中心 RT-Thread-【RA8D1-Vision Board】 RA8D1 Vision Board上的USB實踐RT-Thread問答社區 - RT-Thread 【開發板】環境篇&#xff1a;05燒錄工具介紹_嗶哩嗶哩_bilibili 【RA8D1-Vision Board】基于OpenMV 實現圖像分類_嗶哩嗶哩_…

甘果桌面tv版下載-甘果桌面安卓電視版使用教程

甘果桌面 TV 版是一款備受關注的應用&#xff0c;它可以讓安卓電視的界面更加個性化、操作更加便捷。接下來&#xff0c;我們就詳細了解一下甘果桌面 TV 版的下載方法以及安卓電視版的使用教程。 甘果桌面 TV 版下載 打開你的安卓電視&#xff0c;找到并進入電視自帶的應用商店…

RAII資源管理理解

基礎介紹 RAII (Resource Acquisition Is Initialization) 是一種 C 編程范式&#xff0c;這不是一個語法特性&#xff0c;而是一種處理方式。RAII的思想&#xff1a; 資源獲取與對象初始化同時發生資源釋放與對象銷毀同時發生通過對象的生命周期來管理資源&#xff0c;確保資…

解鎖元生代:ComfyUI工作流與云原生后端的深度融合

目錄 藍耘元生代&#xff1a;智算新勢力崛起? ComfyUI 工作流創建詳解? ComfyUI 初印象? 藍耘平臺上搭建 ComfyUI 工作流? 構建基礎工作流實操? 代碼示例與原理剖析? 云原生后端技術全景 云原生后端概念解析? 核心技術深度解讀? 藍耘元生代中兩者的緊密聯系?…

實戰篇|多總線網關搭建與量產驗證(5000 字深度指南)

引言 1. 環境準備與硬件選型 1.1 項目需求分析 1.2 SoC 與開發板選型 1.3 物理接口與 PCB 設計 1.4 電源與供電保護 2. 軟件架構與協議棧移植 2.1 分層架構詳解 2.2 協議棧移植步驟 2.3 高可用驅動設計 2.4 映射邏輯與 API 定義 3. 開發流程與實踐 3.1 敏捷迭代與里程碑 3.2 核…

Kafka安全認證技術:SASL/SCRAM-ACL方案詳解

#作者 &#xff1a;張桐瑞 文章目錄 1Kafka安全認證技術介紹2基礎設置3 配置SASL/SCRAM認證3.1編寫server.properties配置3.2編寫kafka.conf密碼文件3.3編寫user.properties配置文件3.4編寫kafka-run-class.sh腳本文件3.5Zk中增加kafka用戶3.6啟動kafka進程 1Kafka安全認證技術…

TCP/IP和UDP協議的發展歷程

TCP/IP和UDP協議的發展歷程 引言 互聯網的發展史是人類技術創新的輝煌篇章&#xff0c;而在這一發展過程中&#xff0c;通信協議發揮了奠基性的作用。TCP/IP&#xff08;傳輸控制協議/互聯網協議&#xff09;和UDP&#xff08;用戶數據報協議&#xff09;作為互聯網通信的基礎…

PhotoShop學習10

1.畫板功能的使用 使用畫板功能可以輕松針對不同的設備和屏幕尺寸設計網頁和 APP。畫板是一種容器&#xff0c;類似于特殊圖層組。畫板中的圖層在圖層面板中&#xff0c;按畫板進行分組。 使用畫板&#xff0c;一個文檔中可以有多個設計版面&#xff0c;這樣可以在畫板之間輕…

X-AnyLabeling開源程序借助 Segment Anything 和其他出色模型的 AI 支持輕松進行數據標記。

一、軟件介紹 文末提供源碼和程序下載學習 使用 X-AnyLabeling開源程序可以 導入、管理和保存數據。用戶可以通過多種方式導入圖像和視頻文件&#xff0c;包括快捷方式或菜單選項。此外&#xff0c;它還涵蓋數據刪除、圖像切換以及標簽和圖像數據的保存&#xff0c;以確保高效…

【深度解析】PlatformIO多環境配置實踐:ESP32/ESP32-S3/ESP32-C3適配指南

一、前言&#xff1a;為什么需要多環境配置&#xff1f; 在物聯網開發中&#xff0c;我們經常需要適配不同型號的硬件平臺&#xff08;如ESP32系列&#xff09;,并且github上多數關于ESP32的都適配了多種開發板。傳統開發方式需要為每個平臺維護獨立項目&#xff0c;而Platfor…