Back to Javatutorial

SpringĽӿ

docs/Spring全家桶/Spring/Spring事务基本用法.md

1.0.013.8 KB
Original Source

SpringĽӿ

Spring ǻ AOP ʵֵģ AOP ԷΪλġSpring ԷֱΪΪ뼶ֻͳʱԣЩṩӦõķԡ

Java EE õķֲģʽУSpring λҵ߼㣬ṩĽ

Spring ѹ libs Ŀ¼УһΪ spring-tx-3.2.13.RELEASE.jar ļļ Spring ṩ JAR аĽӿڣPlatformTransactionManagerTransactionDefinition TransactionStatus

JAR ĺ׺ jar ij zip ʽ󣬽ѹѹѹļе \org\springframework\transaction Ŀ¼󣬸Ŀ¼еļͼ 1 ʾ


ͼ 1 Ľӿ

ͼ 1 УעļDZڽҪĺĽӿڡĽӿڵüṩķ¡

1. PlatformTransactionManager

PlatformTransactionManager ӿ Spring ṩƽ̨ڹ񡣸ýӿṩ¡

  • TransactionStatus getTransactionTransactionDefinition definitionڻȡ״̬Ϣ
  • void commitTransactionStatus statusύ
  • void rollbackTransactionStatus statusڻع

ĿУSpring xml õϸϢװ TransactionDefinition УȻͨ getTransaction() ״̬TransactionStatusһIJ

2. TransactionDefinition

TransactionDefinition ӿ壨ĶṩϢȡķа¡

  • String getName()ȡơ
  • int getIsolationLevel()ȡĸ뼶
  • int getPropagationBehavior()ȡĴΪ
  • int getTimeout()ȡijʱʱ䡣
  • boolean isReadOnly()ȡǷֻ

УĴΪָͬһУͬǰʹõ񡣴Ϊ 1 ʾ

ֵ
PROPAGATION_REQUIREDrequiredֵ֧ǰ A ѾУ B ֱʹá򽫴
PROPAGATION_SUPPORTSsupportsֵ֧ǰ A ѾУ B ֱʹáԷ״ִ̬
PROPAGATION_MANDATORYmandatoryֵ֧ǰ A û׳쳣
PROPAGATION_REQUIRES_NEWrequires_newµ A ѾУ A
PROPAGATION_NOT_SUPPORTEDnot_supportedֵ֧ǰԷ״ִ̬С A ѾУ
PROPAGATION_NEVERneverֵ֧ǰ A У׳쳣
PROPAGATION.NESTEDnestedǶ񣬵ײ㽫ʹ Savepoint γǶ

УΪԿǷҪԼδ

ͨ£ݵIJѯıԭݣԲҪݵӡ޸ĺɾȲûָĴΪ Spring3 ĬϵĴΪ required

3. TransactionStatus

TransactionStatus ӿ״̬ijһʱ״̬Ϣа 2 ʾ

<caption> 2 IJ</caption> | | ˵ | | --- | --- | | void flush() | ˢ | | boolean hasSavepoint() | ȡǷڱ | | boolean isCompleted() | ȡǷ | | boolean isNewTransaction() | ȡǷ | | boolean isRollbackOnly() | ȡǷع | | void setRollbackOnly() | ع |

SpringʽXMLʽʵ֣

Spring ַʽһǴͳıʽͨдʵֵһǻ AOP ʵֵʽʵʿУʽʹãֻ Spring ʽϸ⡣

Spring ʽڵײ AOP ŵ̵ͨķʽֻҪļнصĹͿԽӦõҵ߼С

Spring ʵʽҪַʽ

  • XML ʽʽ
  • ͨ Annotation עⷽʽ

ͨת˵İʹ XML ķʽʵ Spring ʽ

1. Ŀ

MyEclipse дһΪ springDemo03 Web Ŀ Spring ֺ֧ JAR Ƶ Web Ŀ lib Ŀ¼Уӵ·¡ӵ JAR ͼ 1 ʾ


ͼ 1 ҪJAR

ͼ 1 пԿӵ spring-tx-3.2.13.RELEASE.jarԼ MySQL JDBC C3P0 JAR

2. ݿ⡢Լ

MySQL дһΪ spring ݿ⣬Ȼڸݿдһ account вݣ SQL ִʾ

CREATE DATABASE spring;
USE spring;
CREATE TABLE account (
id INT (11) PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
money INT DEFAULT NULL
);
INSERT INTO account VALUES (1,'zhangsan',1000);
INSERT INTO account VALUES (2,'lisi',1000);

ִк account еͼ 2 ʾ


ͼ 2 ִн

3. c3p0-db.properties

Ŀ src ´һΪ c3p0-db.properties ļʹ C3P0 ԴҪڸļã

jdbc.driverClass = com.mysql.jdbc.Driver  
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/spring  
jdbc.user = root  
jdbc.password = root  

4. ʵ DAO

1 AccountDao ӿ

Ŀ src Ŀ¼´һΪ com.mengma.dao İڸð´һӿ AccountDaoڽӿдտķʾ

package com.mengma.dao;  
public interface AccountDao {  
    //   
    public void out(String outUser, int money);  
    // տ  
    public void in(String inUser, int money);} ````  
У out()  in() ֱڱʾտ  
  
#### 2DAOӿʵ  
  
Ŀ src Ŀ¼´һΪ com.mengma.dao.impl İڸð´ʵ AccountDaoImplʾ  

package com.mengma.dao.impl;

import org.springframework.jdbc.core.JdbcTemplate;
import com.mengma.dao.AccountDao;

public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; }
// ʵַ
public void out(String outUser, int money) { this.jdbcTemplate.update("update account set money =money-?" + "where username =?", money, outUser); }
// տʵַ
public void in(String inUser, int money) { this.jdbcTemplate.update("update account set money =money+?" + "where username =?", money, inUser); }} ````
Уʹ JdbcTemplate update() ʵ˸²

5. ʵ Service

1 Service ӿ

Ŀ src Ŀ¼´һΪ com.mengma.service İڸð´ӿ AccountServiceʾ

package com.mengma.service;  
  
public interface AccountService {  
    // ת  
    public void transfer(String outUser, String inUser, int money);} ````  
#### 2 Service ӿʵ  
  
Ŀ src Ŀ¼´һΪ com.mengma.service.impl İڸð´ʵ AccountServiceImplʾ  

package com.mengma.service.impl;

import com.mengma.dao.AccountDao;

public class AccountServiceImpl {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; }
public void transfer(String outUser, String inUser, int money) { this.accountDao.out(outUser, money); this.accountDao.in(inUser, money); }} ````
пԿʵ AccountService ӿڣת˵ķʵ֣ݲIJͬ DAO Ӧķ

6. Spring ļ

Ŀ src Ŀ¼´ Spirng ļ 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:context="http://www.springframework.org/schema/context"    xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context.xsd            http://www.springframework.org/schema/tx            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd            http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">    <!-- propertiesļ -->    <context:property-placeholder location="classpath:c3p0-db.properties" />    <!-- ԴȡpropertiesļϢ -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="${jdbc.driverClass}" />        <property name="jdbcUrl" value="${jdbc.jdbcUrl}" />        <property name="user" value="${jdbc.user}" />        <property name="password" value="${jdbc.password}" />    </bean>    <!-- jdbcģ -->    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- dao -->  
    <bean id="accountDao" class="com.mengma.dao.impl.AccountDaoImpl">        <property name="jdbcTemplate" ref="jdbcTemplate" />    </bean>    <!-- service -->  
    <bean id="accountService" class="com.mengma.service.impl.AccountServiceImpl">        <property name="accountDao" ref="accountDao" />    </bean>    <!-- Դ -->    <bean id="txManager"        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- д֪ͨǿ֪ͨҪд;ִϸ -->    <tx:advice id="txAdvice" transaction-manager="txManager">        <tx:attributes>            <!-- 㷽飬nameʾƣ*ʾⷽƣpropagationôΪread-onlyʾ뼶Ƿֻ -->            <tx:method name="find*" propagation="SUPPORTS"                rollback-for="Exception" />            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"                read-only="false" />        </tx:attributes>    </tx:advice>    <!-- aopдSpringԶĿɴҪʹAspectJıʽ -->    <aop:config>        <!--  -->        <aop:pointcut expression="execution(* com.mengma.service.*.*(..))"            id="txPointCut" />        <!-- 棺֪ͨ -->        <aop:advisor pointcut-ref="txPointCut" advice-ref="txAdvice" />    </aop:config></beans> ````  
У <beans> ǵĵ 613  14 дֱ AOP ռ 4250 дʹ <tx:advice> ֪ͨݡ  
  
 5258 дʹ  Ƕ棬е 54 дӦ AspectJ ʽ com.mengma.service зӦ򣬵 57 дʹ  ǽ֪ͨϣ AOP ʽɡ  
  
#### 7\.   
  
Ŀ src Ŀ¼´ com.mengma.test İڸð´ AccountTestʾ  

package com.mengma.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mengma.service.AccountService;
public class AccountTest {
@Test public void test() { // Spring
String xmlPath = "applicationContext.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext( xmlPath); AccountService accountService = (AccountService) applicationContext .getBean("accountService"); accountService.transfer("zhangsan", "lisi", 100); }} ````
ģתҵ񣬴 zhangsan ˻ lisi ˻ת 100 Ԫʹ JUnit test() гɹ󣬲ѯ account ͼ 3 ʾ

ͼ 3 IJѯпԿzhangsan ɹ lisi ת 100 Ԫ


ͼ 3 ѯ

ͨ޸İģתʧܵڵ transfer() һд롰int i=1/0ģϵͳϵʾ

 public void transfer(String outUser, String inUser, int money) {    this.accountDao.out(outUser, money);    //ģϵ  
    int i = 1/0;    this.accountDao.in(inUser, money);
 } 

² test() JUnit ̨Ϣͼ 4 ʾ


ͼ 4 ̨

ͼ 4 пԿִвԷʱ˳ 0 쳣Ϣʱٴβѯ account ѯͼ 5 ʾ

ͼ 5 IJѯпԿеݲûз仯ڳִй׳쳣ύתʧܡɴ˿֪Spring Чˡ


ͼ 5 ѯ

SpringʽAnnotationעⷽʽʵ֣

Spring Уʹû XML ķʽʵʽ⣬ͨ Annotation עķʽʵʽ

ʹ Annotation ķʽdz򵥣ֻҪĿ£¡

1 Spring עʾ

<tx:annotation-driven transaction-manager="txManager"/>

2Ҫʹҵ߷ע @Transactional @Transactional IJ @Transactional IJͼ 1 ʾ


ͼ 1 @Transactionalб

ͨ޸ġ SpringXMLʵ̳ת˵İʹ Annotation עķʽʵ Spring ʽ

1. ע

޸ Spring ļ 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:context="http://www.springframework.org/schema/context"    xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd            http://www.springframework.org/schema/context  
http://www.springframework.org/schema/context/spring-context.xsd            http://www.springframework.org/schema/tx            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd            http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">    <!-- propertiesļ -->    <context:property-placeholder location="classpath:c3p0-db.properties" />    <!-- ԴȡpropertiesļϢ -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="${jdbc.driverClass}" />        <property name="jdbcUrl" value="${jdbc.jdbcUrl}" />        <property name="user" value="${jdbc.user}" />        <property name="password" value="${jdbc.password}" />    </bean>    <!-- jdbcģ -->    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- dao -->  
<bean id="accountDao" class="com.mengma.dao.impl.AccountDaoImpl">        <property name="jdbcTemplate" ref="jdbcTemplate" />    </bean>    <!-- service -->  
<bean id="accountService" class="com.mengma.service.impl.AccountServiceImpl">        <property name="accountDao" ref="accountDao" />    </bean>    <!-- Դ -->    <bean id="txManager"        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- ע -->    <tx:annotation-driven transaction-manager="txManager"/></beans> ````  

пԿԭļȣֻ޸֣Ӳע

Ҫעǣѧϰ AOP עⷽʽʱҪļпע⴦ָɨЩµע⣬ûпע⴦Ϊڵ 3335 ֶ AccountServiceImpl @Transactional עڸУԻֱЧ

2. @Transactional ע

޸ AccountServiceImplļ @Transactional ע⼰Ӻʾ

package com.mengma.service.impl;  
  
import org.springframework.transaction.annotation.Isolation;  
import org.springframework.transaction.annotation.Propagation;  
import org.springframework.transaction.annotation.Transactional;  
  
import com.mengma.dao.AccountDao;  
  
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)  
public class AccountServiceImpl {  
    private AccountDao accountDao;  
    public void setAccountDao(AccountDao accountDao) {        this.accountDao = accountDao;    }  
    public void transfer(String outUser, String inUser, int money) {        this.accountDao.out(outUser, money);        // ģϵ  
        int i = 1 / 0;        this.accountDao.in(inUser, money);    
}}

Ҫעǣʹ @Transactional עʱ֮áзָ

ʹ JUnit ٴ test() ʱ̨ͬͼ 2 ʾ쳣Ϣ˵ʹû Annotation עķʽͬʵ Spring ʽע͵ģϵĴвԣת˲ɡ


ͼ 2 н

ο

https://www.w3cschool.cn/wkspring
https://www.runoob.com/w3cnote/basic-knowledge-summary-of-spring.html
http://codepub.cn/2015/06/21/Basic-knowledge-summary-of-Spring
https://dunwu.github.io/spring-tutorial
https://mszlu.com/java/spring
http://c.biancheng.net/spring/aop-module.html