Evgeniy Krivosheev Vyacheslav Yakovenko Last update: Feb, 2012 Spring Framework Module 7 – Transactions.

Презентация:



Advertisements
Похожие презентации
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Advertisements

© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
1 © Luxoft Training 2013 Spring Framework Module 10 JMS & EJB.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
© 2002 IBM Corporation Confidential | Date | Other Information, if necessary © Wind River Systems, released under EPL 1.0. All logos are TM of their respective.
Evgeniy Krivosheev Vyacheslav Yakovenko Last update: Feb, 2012 Spring Framework Module 4 – JNDI.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Using Multihomed BGP Networks.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
Evgeniy Krivosheev Andrey Stukalenko Vyacheslav Yakovenko Last update: Nov, 2013 Spring Framework Module 1 - Introduction.
Unit II Constructor Cont… Destructor Default constructor.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Implementing Changes in BGP Policy.
SPLAY TREE The basic idea of the splay tree is that every time a node is accessed, it is pushed to the root by a series of tree rotations. This series.
© 2006 Cisco Systems, Inc. All rights reserved.BCMSN v Defining VLANs Correcting Common VLAN Configuration Errors.
© 2009 Avaya Inc. All rights reserved.1 Chapter Four, UMS Web Services Module Three – Exchange 2007.
© 2006 Cisco Systems, Inc. All rights reserved. SND v Configuring a Cisco IOS Firewall Configuring a Cisco IOS Firewall with the Cisco SDM Wizard.
PAT312, Section 21, December 2006 S21-1 Copyright 2007 MSC.Software Corporation SECTION 21 GROUPS.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Optimizing BGP Scalability Implementing BGP Peer Groups.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Attributes Setting BGP Local Preferences.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Customer-to-Provider Connectivity with BGP Connecting a Multihomed Customer to Multiple Service.
Транксрипт:

Evgeniy Krivosheev Vyacheslav Yakovenko Last update: Feb, 2012 Spring Framework Module 7 – Transactions

2 Contents ACID Transaction types Overview of API Isolation Levels Transactions Propagation Using AOP in Transaction Management Programmatic Transaction Management Examples Exercises

3 Spring :: Tx :: ACID Transaction is a group of operations that have ACID properties: Atomicity: either all actions occur, or nothing occurs; Consistency: once a transaction has completed (successfully or not), the data is in consistent state; Isolation: multiple users are allowed to process the same data at the same time; Durability: once a transaction has completed, its result should be durable;

4 Spring :: Tx :: Transaction Transfer X dollars from A account to B account А = А-Х B=B+X Transaction begins Transacation commit Consistent DB state BEGIN COMMIT Read А Subtract Х from А Save А А is blocked for writing or for reading and writing until the end of the transaction

5 Spring :: Tx :: ACID Transfer X dollars from A account to B account А = А-Х B=B+X Transaction begins Transacation commit Transaction rollback Transaction rollback Consistent DB state Not enough money? The account is blocked? BEGIN COMMITROLLBACK

6 Spring :: Tx :: ACID Transfer X dollars from A account to B account А = А-Х B=B+X Transaction begins Transacation commit Consistent DB state А = А-Y Transaction begins Blocking transaction until previous transaction is finished

7 Spring :: Tx :: Transactions types Local: transaction into the single data source; Global: distributed transactions in more than one data source; managed by the application server, using JTA (Java Transaction API);

8 transaction dispatcher Spring :: Tx :: Distributed transactions Transfer X dollars from A account in one bank to B account in another bank А = А-Х B=B+X Transaction begin Transaction begin Transaction prepared Transaction prepared Transaction fixed Transaction fixed Transaction prepared Transaction prepared Transaction rollback Transaction rollback Transaction begin Transaction begin COMMIT PREPARED COMMIT PREPARED ROLLBACK PREPARED

9 Spring :: Tx Transactions support model used in Spring Framework is applicable to different transaction APIs such as JDBC, Hibernate, JPA, JDO, etc. Benefits: Application server is NOT required; Declarative transaction management.

10 Spring :: Tx API The key Spring transaction abstraction is defined by interface: org.springframework.transaction.PlatformTransactionManager public interface PlatformTransactionManager { // create transaction by definition TransactionStatus getTransaction (TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; } Most widely-used implementations: DataSourceTransactionManager ; HibernateTransactionManager ; JmsTransactionManager ; JmsTransactionManager102 ; JpaTransactionManager ; OC4JJtaTransactionManager ; WebLogicJtaTransactionManager ; WebSphereUowTransactionManager

11 Spring :: Tx API TransactionDefinition is used to set parameters of the transaction: org.springframework.transaction.TransactionDefinition TransactionDefinition parameters: Isolation – isolation level of the transaction; Propagation – transaction propagation – how transactions are propagate from one method to another; Timeout ; Read-only status ;

12 Spring :: Tx API In case of declarative transactions, TransactionDefinition is created implicitly through annotations = true) public class DefaultFooService implements FooService { public Foo getFoo(String fooName) { // do something = false, propagation = Propagation.REQUIRES_NEW) public void updateFoo(Foo foo) { // do something }

13 Spring :: Tx API You need to this directive to application context: And add one of the transaction managers to the context:

14 Isolation level Phantom reading Unrepe- atable read «Dirty» readLost update ISOLATION_READ_UNCOMMITTED READ UNCOMMITTED –––+ ISOLATION_READ_COMMITTED READ COMMITTED ––++ ISOLATION_REPEATABLE_READ REPEATABLE READ –+++ ISOLATION_SERIALIZABLE SERIALIZABLE++++ Spring :: Tx :: Transaction isolation levels

15 Spring :: Tx :: Dirty read Transfer Х dollars from А account to В account А = А-Х B=B+X Transaction begin Transaction commit Consistent DB state Read A and B Transaction begin Money was withdrawn from A account, but has not come to B account yet.

16 Spring :: Tx :: Dirty read А = А-Х B=B+X Transaction begin Transaction commit Consistent DB state Read A and B Transaction begin How much money does client have(А+B)? Few money, not enough for operating costs Client is bankrupt! Transfer Х dollars from А account to В account

17 Spring :: Tx :: Unrepeatable read Money withdraw from account А by 2 parallel transactions: Is there enough money on A account? YES А=А-X Transaction begin Consistent DB state A = A-Y Transaction begin Money was withdrawn from A account, but has not come to B account yet – we have «dirty» data. Transaction commit A<0! No money! Transaction rollback A<0! No money! Transaction rollback

18 Spring :: Tx :: Phantom read During transaction 2 in BALANCE table appeared some new data, satisfying the search criteria. Begin transaction 1 How much money does client have? A+B=-1000 How much money does client have? A+B=-1000 Add result to BALANCE table Begin transaction 2 How many clients have negative balance? 0 select count(*) where Balance<0 How many clients have negative balance? 0 select count(*) where Balance<0 How many clients have negative balance? 1 Transaction commit SurnameBalance Smith500 Johnson-1000 Baker9000 Transaction commit

19 Isolation level Phantom reading Unrepe- atable read «Dirty» readLost update ISOLATION_READ_UNCOMMITTED READ UNCOMMITTED –––+ ISOLATION_READ_COMMITTED READ COMMITTED ––++ ISOLATION_REPEATABLE_READ REPEATABLE READ –+++ ISOLATION_SERIALIZABLE SERIALIZABLE++++ Spring :: Tx :: Isolation levels Enum org.springframework.transaction.annotation.Isolation

20 Spring :: Tx + AOP

21 Spring :: Tx :: Propagation Transaction propagation: what happens to transaction when method is called? Spring supports the follow list of propagation: Enum org.springframework.transaction.annotation.Propagation : Required, RequiresNew, Mandatory, NotSupported, Supports, Never

22 Transaction attribute Client transactionTransaction in business method Required – If transaction was started – it uses it. If not – start the new transaction NoT2 T1 RequiresNew – If method () is invoked within the context of another transaction, it will be suspended and a new transaction will be started. Once method() ends, new transaction is either committed or rolled back, and first transaction resumes. NoT2 T1T2 Mandatory – Check for the opened transaction. If transaction was not started, throwsTransactionRequiredException. NoError T1 NotSupported – Suspend current transaction if it was started. No T1No Supports – Use current transaction. If there was no transaction, it works without transaction. No T1 Never – If there was a transaction, generate exception RemoteException. No T1Error Spring :: Tx :: Propagation org.springframework.transaction.annotation.Propagation

23 If the Required transaction attribute is the most commonly used transaction attribute and is the default for both EJB 3.0 and Spring. Unfortunately, in many cases, it is used incorrectly, resulting in data-integrity and consistency issues. If the Mandatory transaction attribute is used in the Client Orchestration transaction strategy which is used when multiple server-based or model-based calls from the client layer fulfill a single unit of work. The client layer in this regard can refer to calls made from a Web framework, portal application, desktop system, or in some cases, a workflow product or business process management (BPM) component. In essence, the client layer owns the processing flow and "steps" needed to complete a particular request. The RequiresNew This transaction attribute should only be used for database operations (such as auditing or logging) that are independent of the underlying transaction. This attribute actually violates ACID criteria (specifically the atomicity property). In other words, all database updates are no longer contained within a single unit of work. If first transaction were to be rolled back, the changes committed by new transaction remain committed. Spring :: Tx :: Propagation Transaction propagation use cases:

24 Supports transaction attribute. This attribute is primarily used for read-only operations to the database. If that's the case, why not specify the NotSupported transaction attribute instead? After all, that attribute guarantees that the method will run without a transaction. Invoking the query operation in the context of an existing transaction will cause data to be read from the database transaction log (in other words, updated data), whereas running without a transaction scope will case the query to read unchanged data from the table. NotSupported transaction attribute. If you try to invoke a database stored procedure within the scope of an existing transaction context and the database stored procedure contains a BEGIN TRANS, an exception will be thrown indicating that a new transaction cannot be started if one already exists. (In other words, nested transactions are not supported.) Almost all containers use the Java Transaction Service (JTS) as the default transaction implementation for JTA. It's JTS not the Java platform per se that doesn't support nested transactions. If you cannot change the database stored procedure, you can use the NotSupported attribute to suspend the existing transaction context to avoid this fatal exception. Never transaction attribute. The only use case I have been able to come up with for this transaction attribute is for testing. It provides a quick and easy way of verifying that a transaction exists when you invoke a particular method. If you use the Never transaction attribute and receive an exception when invoking the method in question, you know a transaction was present. If the method is allowed to execute, you know a transaction was not present. Spring :: Tx :: Propagation Transaction propagation use cases:

25 Spring :: Tx :: Examples Lets study some examples of specific transaction management implementations in application context

26 Spring :: Tx :: Examples DataSourceTransactionManager:

27 Spring :: Tx :: Examples JtaTransactionManager in J2EE container:

28 Spring :: Tx :: Rollback Default Rollback rules: They enable us to specify which exceptions should cause automatic roll back; By default, transactions are rolled back only with RuntimeException ; There are no exceptions for Exception; This behavior can be = IOException.class, noRollbackFor = RuntimeException.class) public void doSomething() { … }

29 PropertyTypeDescription propagationenum: PropagationOptional propagation setting. isolationenum: IsolationOptional isolation level. readOnlyBoolean Read/write vs. read-only transaction. Read-only transaction may work faster and block less resources. timeoutint (seconds) Transaction timeout after which transaction will automatically rollout. rollbackFor Array of Class objects, which must be derived from Throwable. Optional array of exception classes that must cause rollback. rollbackForClassname Array of class names. Classes must be derived from Throwable. Optional array of names of exception classes that must cause rollback. noRollbackFor Array of Class objects, which must be derived from Throwable. Optional array of exception classes that must not cause rollback. noRollbackForClassname Array of String class names, which must be derived from Throwable. Optional array of names of exception classes that must not cause annotation properties: Spring :: Tx

30 Spring :: Tx :: applied to: Interfaces; Classes; Interface methods; Class public methods; It is better to to specific classes and their methods, not to interfaces

31 Spring :: Tx :: Programmatic management Generally, declarative transaction management is used Especially, if there are many transactions in application Programmatic management is used in case: There are few transactions in application; TransactionTemplate can be used, but it is not advisable; Transaction name has to be specified explicitly.

32 Spring :: Tx :: Programmatic management One possible option is using TransactionTemplate:

33 Spring :: Tx :: Programmatic management In this case all properties can be defined programmatically:

34 Spring :: Tx :: Programmatic management In this case all properties can be defined programmatically : TransactionTemplate supports callback approach; Implement TransactionCallback using doInTransaction() method; Pass it to execute() method exposed on the TransactionTemplate;

35 Spring :: Tx :: Configuration Example <aop:pointcut id="defaultServiceOperation expression="execution(*x.y.service.*Service.*(..))"/> <aop:pointcut id="noTxServiceOperation expression="execution(* x.y.service.ddl.DefaultDdlManager.*(..))"/>

36 Exercises 8 : Transaction management in Spring – 30 min for practice;

37 Any questions!?