Spring 黑馬程序員四天筆記(第四天:JdbcTemplate、Spring事務管理)

第1章 Spring 中的 JdbcTemplate[會用]

1.1JdbcTemplate 概述

它是 spring 框架中提供的一個對象,是對原始 Jdbc API 對象的簡單封裝。spring 框架爲我們提供了很多 的操作模板類。

操作關係型數據的:

        JdbcTemplate

HibernateTemplate 操作 nosql 數據庫的:

    RedisTemplate

操作消息隊列的:

JmsTemplate
我們今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我們在導包的時候,除了要導入這個 jar 包

外,還需要導入一個 spring-tx-5.0.2.RELEASE.jar(它是和事務相關的)。

1.2JdbcTemplate 對象的創建

我們可以參考它的源碼,來一探究竟:

public JdbcTemplate() { }
public JdbcTemplate(DataSource dataSource) { 
setDataSource(dataSource);
afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();
    }

除了默認構造函數之外,都需要提供一個數據源。既然有 set 方法,依據我們之前學過的依賴注入,我們可以在配置文件中配置這些對象。

1.3spring 中配置數據源

1.3.1 環境搭建

1.3.2 編寫 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">
</beans>
 

1.3.3 配置數據源

我們之前已經接觸過了兩個數據源,C3P0 和 DBCP。要想使用這兩數據源都需要導入對應的 jar 包。

1.3.3.1 配置 C3P0 數據源

導入 到工程的 lib 目錄。在 spring 的配置文件中配置:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver">
</property> 
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02">
</property> 
<property name="user" value="root">
</property>
 <property name="password" value="1234">
</property> 
</bean>

1.3.3.2 配置 DBCP 數據源

導入 到工程的 lib 目錄。在 spring 的配置文件中配置:

<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property> 
<property name="url" value="jdbc:mysql:// /spring_day02">
</property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property> <property name="url" value="jdbc:mysql:// /spring_day02">
</property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property> 
</bean>

1.3.3.3 配置 spring 內置數據源

spring 框架也提供了一個內置數據源,我們也可以使用 spring 的內置數據源,它就在 spring-jdbc-5.0.2.REEASE.jar 包中:

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property> <property name="url" value="jdbc:mysql:///spring_day02">
</property> 
<property name="username" value="root"></property>
<property name="password" value="1234"></property> 
</bean>

1.3.4 將數據庫連接的信息配置到屬性文件中:

【定義屬性文件】

jdbc.driverClass=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root 
jdbc.password=123

【引入外部的屬性文件】

一種方式 :

<!-- 引入外部屬性文件: -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/> 
</bean>

另一種方式 :

<context:property-placeholder location="classpath:jdbc.properties"/>

1.4JdbcTemplate 的增刪改查操作

1.4.1 前期準備

創建數據庫:

create database spring_day02; 
use spring_day02;

創建表:

create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
 

1.4.2 在 spring 配置文件中配置 JdbcTemplate

<?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">
<!-- 配置一個數據庫的操作模板:JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource">
</property> 
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property> <property name="url" value="jdbc:mysql:///spring_day02">
</property> <property name="username" value="root">
</property>
<property name="password" value="1234">
</property>
</bean>
</beans>

1.4.3 最基本使用

public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據 id 獲取 bean 對象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
//3.執行操作
jt.execute("insert into account(name,money)values('eee',500)"); }
}

1.4.4 保存操作

public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
//2.根據 id 獲取 bean 對象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.執行操作
//保存
jt.update("insert into account(name,money)values(?,?)","fff",5000);
}
}

1.4.5 更新操作

public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
//2.根據 id 獲取 bean 對象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
//3.執行操作
//修改
jt.update("update account set money = money-? where id = ?",300,6); }
}

1.4.6 刪除操作

public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
//2.根據 id 獲取 bean 對象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.執行操作
//刪除
jt.update("delete from account where id = ?",6);
}
}

1.4.7 查詢所有操作

public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據 id 獲取 bean 對象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
//3.執行操作
//查詢所有
List<Account> accounts = jt.query("select * from account where money > ? ", new AccountRowMapper(), 500);
for(Account o : accounts){ System.out.println(o);
}
} }
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException { 
Account account = new Account();
account.setId(rs.getInt("id")); account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account; }
}

1.4.8 查詢一個操作

使用 RowMapper 的方式:常用的方式


public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
//2.根據 id 獲取 bean 對象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
//3.執行操作
//查詢一個
List<Account> as = jt.query("select * from account where id = ? ",
new AccountRowMapper(), 55);
System.out.println(as.isEmpty()?"沒有結果":as.get(0)); }
}

使用 ResultSetExtractor 的方式:不常用的方式

public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
//2.根據 id 獲取 bean 對象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
//3.執行操作
//查詢一個
Account account = jt.query("select * from account where id = ?",
new AccountResultSetExtractor(),3); System.out.println(account);
} }

1.4.9 查詢返回一行一列操作

public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
//2.根據 id 獲取 bean 對象JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.執行操作
//查詢返回一行一列:使用聚合函數,在不使用 group by 字句時,都是返回一行一列。最長用的
就是分頁中獲取總記錄條數
Integer total = jt.queryForObject("select count(*) from account where money > ?
",Integer.class,500); System.out.println(total);
} }

1.5 在 dao 中使用 JdbcTemplate

1.5.1 準備實體類

/**
* 賬戶的實體 */
public class Account implements Serializable {
private Integer id; 
private String name; 
private Float money;
 
public Integer getId() { 
return id;
}
public void setId(Integer id) {
this.id = id; }
public String getName() { 
return name;
}
public void setName(String name) { 
this.name = name;
}
public Float getMoney() {
return money; }
public void setMoney(Float money) {
this.money = money; }
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
 } }

1.5.2 第一種方式:在 dao 中定義 JdbcTemplate

/**
* 賬戶的接口
*/
public interface IAccountDao {
/**
* 根據 id 查詢賬戶信息 * 
@param id
* @return
 */
Account findAccountById(Integer id);
/**
* 根據名稱查詢賬戶信息 * 
@return
*/
Account findAccountByName(String name);
/**
* 更新賬戶信息
* @param account */
void updateAccount(Account account); }
/**
* 賬戶的持久層實現類
* 此版本的 dao,需要給 dao 注入 JdbcTemplate
*/
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountById(Integer id) {
List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0); }
@Override
public Account findAccountByName(String name) {
List<Account> list = jdbcTemplate.query("select * from account where name
= ? ",new AccountRowMapper(),name); if(list.isEmpty()){
return null; }
if(list.size()>1){
throw new RuntimeException("結果集不唯一,不是隻有一個賬戶對象");
}
return list.get(0); }
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ?
",account.getMoney(),account.getId()); }
}

配置文件

<?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">
<!-- 配置一個 dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!-- 注入 jdbcTemplate -->
<property name="jdbcTemplate" ref="jdbcTemplate">
</property>
</bean>
<!-- 配置一個數據庫的操作模板:JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource">
</property> 
</bean>    
!-- 配置數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql:///spring_day04">
</property> 
<property name="username" value="root">
</property>
<property name="password" value="1234">
</property>
    </bean>
</beans>

思考:

此種方式有什麼問題 嗎 ?

答案:

有個小問題。就是我們的 dao 有很多時,每個 dao 都有一些重複性的代碼。下面就是重複代碼:

private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { 
this.jdbcTemplate = jdbcTemplate;
}

能不能把它抽取出來呢? 請看下一小節。

1.5.3 第二種方式:讓 dao 繼承 JdbcDaoSuppor

JdbcDaoSupport 是 spring 框架爲我們提供的一個類,該類中定義了一個 JdbcTemplate 對象,我們可以 直接獲取使用,但是要想創建該對象,需要爲其提供一個數據源:具體源碼如下:

public abstract class   extends DaoSupport {
JdbcDaoSupport
{
//定義對象
private JdbcTemplate jdbcTemplate;
//set 方法注入數據源,判斷是否注入了,注入了就創建 JdbcTemplate public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) //如果提供了數據源就創建 JdbcTemplate
this.jdbcTemplate = createJdbcTemplate(dataSource);
    initTemplateConfig();
}
}
//使用數據源創建 JdcbTemplate
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource); }
//當然,我們也可以通過注入 JdbcTemplate 對象
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
    initTemplateConfig();
}
//使用 getJdbcTmeplate 方法獲取操作模板對象
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate; }
/**
* 賬戶的接口
*/
public interface IAccountDao {
/**
* 根據 id 查詢賬戶信息 * @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 根據名稱查詢賬戶信息 * @return
*/
Account findAccountByName(String name);
/**
* 更新賬戶信息
* @param account
*/
void updateAccount(Account account);
}
/**
* 賬戶的持久層實現類
* 此版本 dao,只需要給它的父類注入一個數據源 */
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
//getJdbcTemplate()方法是從父類上繼承下來的。
List<Account> list = getJdbcTemplate().query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0); }
@Override
public Account findAccountByName(String name) {
//getJdbcTemplate()方法是從父類上繼承下來的。
List<Account> list = getJdbcTemplate().query("select * from account where name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){ return null;
} if(list.size()>1){
throw new RuntimeException("結果集不唯一,不是隻有一個賬戶對象"); }
return list.get(0); }
@Override
public void updateAccount(Account account) {
//getJdbcTemplate()方法是從父類上繼承下來的。
getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
}
}

配置文件:

<?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">
<!-- 配置 dao2 -->
<bean id="accountDao2" class="com.itheima.dao.impl.AccountDaoImpl2"> <!-- 注入 dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring_day04"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property> 
</bean>
</beans>

思考:

兩版 Dao 有什麼區別呢? 答案:

第一種在 Dao 類中定義 JdbcTemplate 的方式,適用於所有配置方式(xml 和註解都可以)。

第二種讓 Dao 繼承 JdbcDaoSupport 的方式,只能用於基於 XML 的方式,註解用不了。

第2章 Spring 中的事務控制

2.1 Spring 事務控制我們要明確的

第一:JavaEE 體系進行分層開發,事務處理位於業務層,Spring 提供了分層設計業務層的事務處理解決方 案。

第二:spring 框架爲我們提供了一組事務控制的接口。具體在後面的第二小節介紹。這組接口是在 spring-tx-5.0.2.RELEASE.jar 中。

第三:spring 的事務控制都是基於 AOP 的,它既可以使用編程的方式實現,也可以使用配置的方式實現。我 們學習的重點是使用配置的方式實現。

2.2 Spring 中事務控制的 API 介紹

2.2.1 PlatformTransactionManager

此接口是 spring 的事務管理器,它裏面提供了我們常用的操作事務的方法,如下圖:

我們在開發中都是使用它的實現類,如下圖:

2.2.2 TransactionDefinition

它是事務的定義信息對象,裏面有如下方法:

2.2.2.1 事務的隔離級別

2.2.2.2 事務的傳播行爲

2.2.2.3 超時時間

默認值是-1,沒有超時限制。如果有,以秒爲單位進行設置。

2.2.2.4 是否是隻讀事務

建議查詢時設置爲只讀。

2.2.3 TransactionStatus

此接口提供的是事務具體的運行狀態,方法介紹如下圖:

2.3基於 XML 的聲明式事務控制(配置方式)重點

2.3.1 環境搭建

2.3.1.1 第一步:拷貝必要的 jar 包到工程的 lib 目錄

2.3.1.2 第二步:創建 spring 的配置文件並導入約束

此處需要導入 aop 和 tx 兩個名稱空間

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

2.3.1.3 第三步:準備數據庫表和實體類

創建數據庫:

create database spring_day04;
use spring_day04;

創建表:

create table account(
    id int primary key auto_increment,
    name varchar(40),
    money float
)character set utf8 collate utf8_general_ci;
/**
* 賬戶的實體
*/
public class Account implements Serializable {
private Integer id; private String name; private Float money;
 
public Integer getId() { return id;
}
public void setId(Integer id) {
this.id = id; }
public String getName() {
return name; }
public void setName(String name) { this.name = name;
}
public Float getMoney() { return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
} }

2.3.1.4 第四步:編寫業務層接口和實現類

/**
* 賬戶的業務層接口 */
public interface IAccountService {
/**
* 根據 id 查詢賬戶信息 * @param id
* @return
*/
Account findAccountById(Integer id);//查
/**
* 轉賬
* @param sourceName 轉出賬戶名稱
* @param targeName 轉入賬戶名稱 * @param money 轉賬金額
*/
void transfer(String sourceName,String targeName,Float money);//增刪改
} /**
* 賬戶的業務層實現類
*/
public class AccountServiceImpl implements IAccountService {
public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer id) { return accountDao.findAccountById(id);
}
@Override
public void transfer(String sourceName, String targeName, Float money) {
//1.根據名稱查詢兩個賬戶
Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targeName); //2.修改兩個賬戶的金額 source.setMoney(source.getMoney()-money);//轉出賬戶減錢
target.setMoney(target.getMoney()+money);//轉入賬戶加錢 //3.更新兩個賬戶
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target); }
}

2.3.1.5 第五步:編寫 Dao 接口和實現類

/**
* 賬戶的持久層接口
*/
public interface IAccountDao {
/**
* 根據 id 查詢賬戶信息
* @param id * @return */
Account findAccountById(Integer id);
/**
* 根據名稱查詢賬戶信息 * @return
 */
Account findAccountByName(String name);
/**
* 更新賬戶信息
* @param account
*/
void updateAccount(Account account);
} /**
* 賬戶的持久層實現類
* 此版本 dao,只需要給它的父類注入一個數據源 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
List<Account> list = getJdbcTemplate().query("select * from account where
id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0); }
@Override
public Account findAccountByName(String name) {
List<Account> list = getJdbcTemplate().query("select * from account where
name = ? ",new AccountRowMapper(),name); if(list.isEmpty()){
return null;
} if(list.size()>1){
throw new RuntimeException("結果集不唯一,不是隻有一個賬戶對象"); }
return list.get(0); }
@Override
public void updateAccount(Account account) {
getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
} }
/**
* 賬戶的封裝類 RowMapper 的實現類
*/
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account(); account.setId(rs.getInt("id")); account.setName(rs.getString("name")); account.setMoney(rs.getFloat("money")); return account;
} }

2.3.1.6 第六步:在配置文件中配置業務層和持久層對象

<!-- 配置 service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!-- 注入 dataSource -->
<property name="dataSource" ref="dataSource"></property> </bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring_day04"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property> </bean>

2.3.2 配置步驟


2.3.2.1 第一步:配置事務管理器

<!-- 配置一個事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入 DataSource -->
<property name="dataSource" ref="dataSource"></property> </bean>

2.3.2.2 第二步:配置事務的通知引用事務管理器

<!-- 事務的配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"> 
</tx:advice>

2.3.2.3 第三步:配置事務的屬性

<!--在 tx:advice 標籤內部 配置事務的屬性 --> 
<tx:attributes>
<!-- 指定方法名稱:是業務核心方法
read-only:是否是隻讀事務。默認 false,不只讀。 isolation:指定事務的隔離級別。默認值是使用數據庫的默認隔離級別。
propagation:指定事務的傳播行爲。
timeout:指定超時時間。默認值爲:-1。永不超時。
rollback-for:用於指定一 個異常,當 執行產生該 異常時,事 務回滾。產 生其他異常 ,事務不回 滾。
沒有默認值,任何異常都回滾。 no-rollback-for:用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時,事務回
 
滾。沒有默認值,任何異常都回滾。
-->
<tx:method name="*" read-only="false" propagation="REQUIRED"/> 
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>

2.3.2.4 第四步:配置 AOP 切入點表達式

<!-- 配置 aop -->
<aop:config>
<!-- 配置切入點表達式 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))"
id="pt1"/> </aop:config>

2.3.2.5 第五步:配置切入點表達式和事務通知的對應關係

 <!-- 在 aop:config 標籤內部:建立事務的通知和切入點表達式的關係 --> 
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>

2.4 基於註解的配置方式

2.4.1 環境搭建
2.4.1.1 第一步:拷貝必備的 jar 包到工程的 lib 目錄

2.4.1.2 第二步:創建 spring 的配置文件導入約束並配置掃描的包

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
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 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 http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置 spring 創建容器時要掃描的包 -->
<context:component-scan base-package="com.itheima"></context:component-scan> 
<!-- 配置 JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置 spring 提供的內置數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/spring_day02">
</property> 
<property name="username" value="root"></property> 
<property name="password" value="1234"></property>
</bean>
</beans>

2.4.1.3 第三步:創建數據庫表和實體類

和基於 xml 的配置相同。略

2.4.1.4 第四步:創建業務層接口和實現類並使用註解讓 spring 管理

/**
* 賬戶的業務層實現類 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService { 
@Autowired
private IAccountDao accountDao; 
//其餘代碼和基於 XML 的配置相同
}

2.4.1.5 第五步:創建 Dao 接口和實現類並使用註解讓 spring 管理

/**
* 賬戶的持久層實現類 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao { 
@Autowired
private JdbcTemplate jdbcTemplate; //其餘代碼和基於 XML 的配置相同
}

2.4.2 配置步驟
2.4.2.1 第一步:配置事務管理器並注入數據源

<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">
</property> 
</bean>

2.4.2.2 第二步:在業務層使用@Transactional 註解

 

 

 

 

 

 

 

 

 

 

@Service("accountService") @Transactional(readOnly=true,propagation=Propagation.SUPPORTS) public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) { 
return accountDao.findAccountById(id);
} @Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public void transfer(String sourceName, String targeName, Float money) {
//1.根據名稱查詢兩個賬戶
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName); 
//2.修改兩個賬戶的金額 source.setMoney(source.getMoney()-money);
//轉出賬戶減錢
target.setMoney(target.getMoney()+money);
//轉入賬戶加錢 
//3.更新兩個賬戶
accountDao.updateAccount(source); 
//int i=1/0; 
accountDao.updateAccount(target);
} }

該註解的屬性和 xml 中的屬性含義一致。該註解可以出現在接口上,類上和方法上。 出現接口上,表示該接口的所有實現類都有事務支持。

出現在類上,表示類中所有方法有事務支持 出現在方法上,表示方法有事務支持。 以上三個位置的優先級:方法>類>接口

2.4.2.3 第三步:在配置文件中開啓 spring 對註解事務的支持

 <!-- 開啓 spring 對註解事務的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

2.4.3 不使用 xml 的配置方式

@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
//裏面配置數據源,配置 JdbcTemplate,配置事務管理器。在之前的步驟已經寫過了。
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章