系列文章
SSM之Spring 01 —— 第一個Spring程式、配置說明、IOC、DI、自動裝配、注解/Java方式開發
SSM之Spring 02 —— 動态代理、AOP、Spring-MyBatis、聲明式事務
文章目錄
- 系列文章
- 10、代理模式
-
- 10.1、靜态代理
- 10.2、加深了解代理
- 10.3、動态代理
- 11、AOP
-
- 11.1、什麼是AOP
- 11.2、Aop在Spring中的作用
- 11.3、使用Srping實作AOP
- 12、整合MyBatis
-
- 12.1、MyBatis回顧
- 12.2、MyBatis-Spring
- 12.3、MyBatis-Spring簡化版
- 13、聲明式事務
-
- 13.1、回顧事務
- 13.2、沒配置事務的情況
- 13.3、AOP 事務
10、代理模式
為什麼要學習代理模式?因為這是Spring AOC的底層【Spring AOP 和 Spring MVC】
代理模式的分類:
- 靜态代理
- 動态代理
代理的概念就像房屋中介,它負責幫房東解決房屋出租的問題,房東隻需要将鑰匙給中介,其他的像廣告宣傳之類的都由代理完成,而租客則無法直接找到房東聯系,也隻能通過中介去完成租房。
10.1、靜态代理
角色分析:
- 抽象角色:一般用接口或抽象類實作,例如房屋出租接口
- 真實角色:被代理的角色,例如房東
- 代理角色:代理真實角色,在代理過程中會做一些附屬操作
- 客戶:通路代理對象的人,例如租客
下面用房屋出租為例:
1、出租房屋操作的接口
public interface Rent {
public void rent();
}
2、真實角色—房東
public class Landlord implements Rent {
public void rent() {
System.out.println("房東要出租房子了!");
}
}
3、代理角色—房屋中介
public class Proxy implements Rent {
Landlord landlord;
public Proxy(Landlord landlord) {
this.landlord = landlord;
}
public void rent() {
seeHouse();
landlord.rent();
sign();
charge();
}
public void seeHouse(){
System.out.println("中介帶你看房~");
}
public void charge(){
System.out.println("收中介費~");
}
public void sign(){
System.out.println("簽合同~");
}
}
4、客戶聯系代理角色
public class Client {
public static void main(String[] args) {
//房東準備出租房子
Landlord landlord = new Landlord();
//中介替房東出租房子,并帶上附屬操作
Proxy proxy = new Proxy(landlord);
//你直接找中介
proxy.charge();
}
}
代理模式優點:
- 可以使真實角色的操作更加純粹,無需去關注一些公共業務,例如房東隻需要出租房
- 公共操作統一交給代理角色,實作了業務的分工
- 公共業務發生擴充時友善管理,例如中介需要增加其他操作時,無需修改房東
代理模式缺點:
- 一個真實角色就會産生一個代理角色,代碼量翻倍,開發效率變低。
10.2、加深了解代理
這裡再舉一個例子,說明代理的必要性!假如我們有一堆業務代碼,實作使用者增删改查,現在希望在不改動原有代碼的基礎上,實作對增删改查的日志。這就可以用代理實作!
//使用者業務層接口
public interface UserService {
public void addUser();
public void deleteUser();
public void updateUser();
public void queryUser();
}
//使用者業務層實作類
public class UserServiceImpl implements UserService{
public void addUser() {
System.out.println("增加了一個使用者");
}
public void deleteUser() {
System.out.println("删除了一個使用者");
}
public void updateUser() {
System.out.println("更新了一個使用者");
}
public void queryUser() {
System.out.println("查詢了一個使用者");
}
}
//使用者業務層代理
public class UserServiceProxy implements UserService {
//Spring不适用new建立對象,而是通過set注入
UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void addUser() {
log("addUser");
userService.addUser();
}
public void deleteUser() {
log("deleteUser");
userService.deleteUser();
}
public void updateUser() {
log("updateUser");
userService.updateUser();
}
public void queryUser() {
log("queryUser");
userService.queryUser();
}
public void log(String message){
System.out.println("執行了"+message+"操作");
}
}
通過代理,我們可以實作橫向開發,即在不改變原有業務的情況下,實作新的操作。
10.3、動态代理
- 動态代理和靜态代理的角色一樣,但克服了靜态代理的缺陷(每個真實角色都要寫一個代理)
- 動态代理的代理類是動态生成的,是以不需要每個不同的真實角色都去寫代理類
- 動态代理分為兩大類:基于接口和基于類
- 基于接口:JDK動态代理(我們現在使用這個)
- 基于類:cglib
- Java位元組碼也能實作:Javassist
基于接口的動态代理需要先了解:Proxy 代理類 和 InvocationHandler 調用處理接口
- Proxy:提供建立動态代理類的靜态方法
- InvocationHandler:調用處理程式接口,需要實作invoke方法
現在我們修改上一個Service層加日志的代碼,UserService和UserServiceImpl不變,使用動态代理:
package com.zcy.demo03;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;//被代理的角色
//設定被代理的角色
public void setTarget(Object target) {
this.target = target;
}
//獲得代理類
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
//處理代理角色,并傳回結果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//執行代理的附屬操作
//通過反射,獲得方法名
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
//設定UserServiceImpl日志
public void log(String message){
System.out.println("執行了"+message+"方法");
}
}
測試:
@Test
public void test(){
//真實角色
UserService userService = new UserServiceImpl();
//代理角色
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//設定要代理的角色為 userService
pih.setTarget(userService);
//動态生成代理類
UserService proxy = (UserService) pih.getProxy();
//執行操作
proxy.queryUser();
proxy.addUser();
proxy.deleteUser();
proxy.updateUser();
}
結果:
代理操作基本是死的模闆,隻需要修改log方法以及invoke裡的操作,由于是基于反射實作的,是以非常靈活!
動态代理優點:
- 一個動态代理類,代理的是一個接口,一般直接就是一類業務,相當于一個模闆。
- 一個動态代理類可以實作了相同接口的多個類。
11、AOP
一句化概括:在不改變原有業務類的情況下,實作動态增強,比如增加些附屬操作。
11.1、什麼是AOP
AOP(Aspect Oriented Programming)即:面向切面程式設計,通過預編譯方式以及動态代理來統一維護程式功能的一種技術。AOP是OOP的延續,是Spring架構的重要内容。利用AOP可以對業務邏輯的各個部分進行隔離,進而降低業務邏輯各部分間的耦合度,提高程式可用性以及開發效率。
11.2、Aop在Spring中的作用
提供聲明式事務:允許使用者自定義切面
- 橫切關注點:跨越應用程式多個子產品的方法或功能。即,與我們業務邏輯無關的,但又需要我們關注的那部分。例如:日志、緩存…
- 切面(aspect):橫切關注點被子產品化後的特殊對象。即,橫切關注點的類。
- 通知(advice):切面必須完成的動作。即,橫切關注點類的一個方法。
- 目标(target):被通知的對象。
- 代理(proxy):向目标對象應用通知後建立的對象
- 切入點(point cut):切面通知 執行的 ”地點“
- 連接配接點(joint point):與切入點比對的執行點
Spring AOP中,通過Advice定義橫切邏輯,Spring中支援5中類型的Advice:
11.3、使用Srping實作AOP
【注意】使用Spring AOP需要導入包aop織入
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
導入XML限制
xmlns:aop="http://www.springframework.org/schema/aop"
//放在xsi:schemaLocation裡
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
方式一:使用Spring的API接口
還是用前面的UserService接口和UserServiceImpl實作類,但新增兩個日志通知類。
public class BeforeLog implements MethodBeforeAdvice {
/**
*
* @param method 要執行的目标對象的方法
* @param args 目标對象的參數
* @param target 目标對象
* @throws Throwable
*/
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被執行前");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue:目标對象方法執行完後的傳回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被執行後");
}
}
applicationContext.xml
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注冊bean -->
<bean id="userService" class="com.zcy.service.UserServiceImpl"/>
<bean id="beforeLog" class="com.zcy.log.BeforeLog"/>
<bean id="afterLog" class="com.zcy.log.AfterLog"/>
<!-- 方式一:使用原生Spring API接口 -->
<!-- 配置AOP:需要先導入AOP限制 -->
<aop:config>
<!-- 切入點:表明要切入的位置,id是該切入點名字 -->
<!-- expression就是位置,其值是一個表達式(第一個*表明修飾符任意,第二個*表明方法任意,(..)表明參數不限) -->
<aop:pointcut id="pointcut" expression="execution(* com.zcy.service.UserServiceImpl.*(..))"/>
<!-- 通知:把beforeLog和afterLog(bean的id)這兩個類切入到pointcut切入點上 -->
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
測試
@Test
public void aopTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.addUser();
}
結果:
方式二:使用自定義類實作(主要是切面方式)
public class DiyPointCut {
public void before(){
System.out.println("======方法執行前=====");
}
public void after(){
System.out.println("======方法執行後======");
}
}
<!-- 注冊bean -->
<bean id="userService" class="com.zcy.service.UserServiceImpl"/>
<!-- 方式二:自定義類 -->
<!-- 注冊自定義類 -->
<bean id="diy" class="com.zcy.log.DiyPointCut"/>
<aop:config>
<!-- 自定義切面,ref是要引入的類 -->
<aop:aspect ref="diy">
<!-- 切入點,切入com.zcy.service.UserServiceImpl下的所有方法且不限參數 -->
<aop:pointcut id="point" expression="execution(* com.zcy.service.UserServiceImpl.*(..))"/>
<!-- 通知:方法前、方法後 -->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
測試結果:
方式三:使用注解實作
package com.zcy.log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class DiyPointCut {
//注意這裡的@Before和@After是aspectj包下的,junit包裡也有這個
@Before("execution(* com.zcy.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("======方法執行前=====");
}
@After("execution(* com.zcy.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("======方法執行後======");
}
//環繞:我們可以給定一個參數,代表我們要擷取處理切入的點
@Around("execution(* com.zcy.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("環繞前");
Object proceed = joinPoint.proceed();//調用後,才開始執行方法
System.out.println("環繞後");
}
}
applicationContext.xml
<!-- 方式三:注解實作AOP -->
<bean id="diy" class="com.zcy.log.DiyPointCut"/>
<!-- 開啟AOP注解支援 -->
<aop:aspectj-autoproxy/>
測試結果:
12、整合MyBatis
中文文檔:http://mybatis.org/spring/zh/index.html
相關jar包
<!-- Junit測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- Lombok 簡化實體類代碼 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- Spring核心框 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.3</version>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!-- 資料庫驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- Spring整合MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- Spring 操作資料庫 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.3</version>
</dependency>
12.1、MyBatis回顧
正常使用MyBatis的流程:
1、編寫核心配置檔案mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.zcy.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.zcy.dao"/>
</mappers>
</configuration>
2、根據資料庫字段建立實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
3、編寫接口
public interface UserMapper {
public List<User> getUser();
}
4、編寫mapper.xml并實作接口的SQL
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zcy.dao.UserMapper">
<select id="getUser" resultType="user">
select * from user
</select>
</mapper>
5、測試
@Test
public void testMyBatis() throws IOException {
//MyBatis核心配置檔案路徑
String resource = "mybatis-config.xml";
//加載核心配置檔案
InputStream is = Resources.getResourceAsStream(resource);
//擷取SqlSession工廠
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
//通過工廠獲得SqlSession,打開資料庫連接配接
SqlSession sqlSession = build.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUser();
for (User user : userList) {
System.out.println(user);
}
}
6、結果
12.2、MyBatis-Spring
使用Spring整合MyBatis,
1、根據資料庫字段編寫實體類User(和前面一樣的)
2、編寫UserMapper接口以及UserMapper.xml(和前面一樣的)
3、UserMapperImpl實作類
之是以要寫實作類,是因為MyBatis僅靠mapper是無法實作Spring注入的,因為沒有set方法,這個實作類就是Spring和MyBatis的關聯。
public class UserMapperImpl implements UserMapper {
//SqlSessionTemplate是Spring中對SqlSession的替代,操作是一樣的
private SqlSessionTemplate sqlSessionTemplate;
//由于Spring通過注入方式指派,是以必須實作set方法
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
//實作接口的方法
public List<User> getUser() {
//獲得Mapper,依然通過Mapper執行接口方法
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.getUser();
}
}
4、編寫Spring配置檔案和MyBatis配置檔案
MyBatis配置檔案:mybatis-config.xml,一般隻寫setting和别名
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="logImpl" value="LOG4J"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.zcy.pojo"/>
</typeAliases>
</configuration>
Spring配置檔案:固定模闆,用于關聯MyBatis的
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 資料源,替代了mybatis-config.xml中的environment -->
<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/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- 獲得SqlSessionFactory的bean,可在這裡設定mybatis-config.xml中的各種參數配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加載資料源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 可綁定MyBatis核心配置檔案 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 注冊Mapper -->
<property name="mapperLocations" value="classpath:com/zcy/mapper/*.xml"/>
<!-- 别名(但一般别名和set标簽還是留在mybatis-config.xml中設定,以便檢視)-->
<property name="typeAliasesPackage" value="com.zcy.pojo"/>
</bean>
<!-- 替代了SqlSession,并實作注入 -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- SqlSessionTemplate沒有set方法,是以隻能使用構造方法注入 -->
<!-- 通過SqlSessionFactory獲得SqlSessionTemplate -->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
Spring配置檔案:真正的配置檔案,同時需要導入上一個配置檔案,并注冊UserMapper接口。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.zcy.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
</beans>
5、測試:通過Spring方式使用MyBatis
@Test
public void testSpringMyBatis(){
//獲得Spring容器,通過該容器擷取Mapper
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//擷取Mapper後,正常使用MyBatis
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.getUser()) {
System.out.println(user);
}
}
結果:
12.3、MyBatis-Spring簡化版
根據官方文檔,我們可以讓接口的實作類去繼承
SqlSessionDaoSupport
,然後就能直接通過
getSqlSession()
獲得
SqlSessionTemplate
。
如此我們便可以省略注入
SqlSessionTemplate
。(但需要注入sqlSessionFactory,因為繼承的父類
SqlSessionDaoSupport
需要)
UserMapperImpl2.java
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
public List<User> getUser() {
return getSqlSession().getMapper(UserMapper.class).getUser();
}
}
spring-dao.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<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/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/zcy/mapper/*.xml"/>
</bean>
<!-- 省略了sqlSessionTemplate注入 -->
</beans>
applicationContext.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userMapper2" class="com.zcy.mapper.UserMapperImpl2">
<!-- 無需注入sqlSessionTemplate,但需要給它的父類注入sqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
13、聲明式事務
13.1、回顧事務
- 把一組業務當成一個業務來做,要麼都成功,要麼都失敗
- 事務在項目開發中十分重要,涉及到資料的一緻性問題!
- 事務ACID原則:
- 原子性 atomicity :事務是一個整體,必須一起完成,不能隻執行一部分
- 一緻性 consistency :一個事務執行前後,資料庫都必須處于一緻狀态,即某些未完成的事務不能寫入資料庫,否則資料庫會不一緻。
- 隔離性 isolation :并發的事務互相隔離,一個事務執行時不被其他事務幹擾
- 髒讀:一個事務讀取了另一個事務還未送出的資料
- 非重複讀:在一個事務内讀取表中的某一行資料,但多次讀取的結果不同
- 幻讀:在一個事務内讀取到其他事務插入的資料,導緻前後讀取不一緻
- 持久性 durability :事務一旦送出,資料一定會被寫入資料庫,無論系統發生聲明問題。
13.2、沒配置事務的情況
考慮下面情況,一組動作中添加使用者、删除使用者、查詢使用者,但删除使用者出現錯誤,是以不應該寫入資料庫,而由于沒有配置事務,雖然最後報錯了,不過添加使用者依然成功執行。
public interface UserMapper {
public List<User> getUser();
public int addUser(User user);
public int deleteUser(int id);
}
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> getUser() {
addUser(new User(3,"老王", "333333"));
deleteUser(3);
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.getUser();
}
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zcy.mapper.UserMapper">
<select id="getUser" resultType="user">
select * from user
</select>
<insert id="addUser" parameterType="user">
insert into user (id, name, password) values (#{id}, #{name}, #{password})
</insert>
<!-- 故意寫錯 deletesss -->
<delete id="deleteUser" parameterType="int">
deletesss from user where id = #{id}
</delete>
</mapper>
結果:
13.3、AOP 事務
Spring中寫事務有兩種方式,但主要還是橫向切入,通過AOP的方式寫事務,這樣可以不用改變原有代碼。
隻需要修改spring-dao.xml
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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
https://www.springframework.org/schema/aop/spring-aop.xsd">
<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/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/zcy/mapper/*.xml"/>
</bean>
<!-- =========== 下面代碼幾乎就是一個模闆!!========== -->
<!-- 配置聲明式事務 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<!-- 結合AOP,實作事務的織入 -->
<!-- 配置事務通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 給哪些方法配置事務 -->
<tx:attributes>
<!-- 設定查詢使用者為隻讀 -->
<tx:method name="getUser" read-only="true"/>
<!-- 所有方法開啟事務:propagation(傳播)=REQUIRED 如果目前沒有事務就建立事務 -->
<!-- 這個配置的意思是:當我調用Service層的方法時,會開啟一個事務。而當我們在這個Service層的方法裡調用其他方法
或者其他Service層的方法時,會直接用目前方法的事務。如果目前方法沒有事務,就會建立事務。
-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事務切入 -->
<aop:config>
<aop:pointcut id="txPoint" expression="execution(* com.zcy.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
</beans>
思考:為什麼需要事務?
- 如果不配置事務,可能存在資料不一緻的情況。
- 如果我們不在Spring中配置聲明式事務,我們就需要在代碼中手動去配置事務。