一起來學大資料|Spring的事務管理,一分錢也不能少
之前我們講過spring是一站式框架,我們已經學習了spring框架簡單的資料操作。今天我們一起來看看spring針對dao層提供的解決技術jdbcTemplate。我們直接以銀行轉賬為例,完成我們資料庫的連線和事務管理。
JdbcTemplate
1、準備工作
準備工作當然還是導包,這裡我們又引入了兩個新的jar包。
2、操作步驟
(1)配置資料庫的相關資訊 DriverManagerDataSource dataSource = new DriverManagerDataSource();
(2)建立jdbcTemplate的物件,傳輸資料庫的資訊
(3)呼叫jdbcTemplate物件中的方法實現crud操作
這種方法配置連線資料庫是十分麻煩的,接下來我們使用連線池來解決這個問題。
Spring配置連線池
我們將上面test中的設定資料庫資訊用連線池替換。
我們看到這裡的資料庫資訊也是寫死的,我們再來升級一下,將資料庫連線資訊提取出去db.properties
,在spring配置檔案中使用資原始檔中資料庫資訊
配置連線池部分具體使用
最終具體的效果圖如下:
Spring的事務管理
1 建立資料庫表,新增測試資料
2 在配置檔案引入完全約束
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
3 完成service、dao和jdbcTemplate注入關係
4 完成轉賬操作
(1)service程式碼
(2)dao程式碼
5 如果lucy少了1000之後,出現異常,mary不會多1000.丟失了,這時候我們就要用新增事務,
事務解決:
第一步 配置事務管理器
第二步 配置事務註解
第三步 在要使用事務的方法所在類上面添加註解
最終的效果圖如下:
dao方法中新增轉入轉出方法,service中統一方法,在test我們進行測試,兩個配置檔案。其中applicationContext.xml檔案具體如下。
這就是今天的內容。明天,我們開始學習SpringMVC。
個人原創,請多多指教。有幫助到大家的話,關注支援一下喲~
感謝堅持關注的朋友~
世界很大,幸好有你~
歡迎在評論區留下你的問題或困惑,我將每天與你分享我的觀點和心得。
聚焦最新科技諮訊,探尋未來智慧領域,我是女陶Mario