JavaEE transaction, javaee

Source: Internet
Author: User

JavaEE transaction, javaee
1. What is a transaction? A Transaction is a series of operations performed as a single logical unit of work. These operations are submitted to the system as a whole, either executed or not executed. A transaction is an inseparable logical unit of work.
Transfer operation A-> B:
Begin transaction
1. Update the balance of account
2. Record the transaction log of account
3. Update the balance of Account B
4. record transaction logs of Account B
End transaction


Ii. ACID Atomicity of transactions
A transaction must be an atomic unit of work. You can modify the data either completely or not.
Consistent Consistency
When the transaction is completed, all data must be consistent. In related databases, all rules must be applied to transaction modifications to maintain the integrity of all data. At the end of the transaction, all internal data structures must be correct. The integrity constraints of the database are not damaged before and after the transaction starts.
Isolation
Modifications made by a concurrent firm must be isolated from those made by any other concurrent firm. The status of the data when the transaction is viewing the data is either the status before the transaction is modified or the status after the transaction is modified. The transaction does not view the data in the intermediate status.
Persistent Durability
After a transaction is completed, its impact on the system is permanent: the changes made by the transaction to the database are permanently stored in the database and will not be rolled back.


Iii. Transaction Management Policy Container management Transaction (CMT Container Manage Transaction)
Bean management Transaction (BMT Bean Manage Transaction)
JTA: Java Transaction API
1. JTA is a series of interfaces provided by JavaEE to manage distributed transactions. It provides communication mechanisms between TransactionManager and ResourceManager.
A. javax. transaction. UserTransaction provides an interface that is directly used by application code to define transaction boundaries and obtain transaction statuses.
B. javax. transaction. TransactionManager is mainly used by the application server. In addition to defining the transaction boundary and obtaining the transaction status, you can also suspend (suspend) or restart (resume) the transaction.


Iv. transaction attribute Required:
A method call requires the transaction context. If a transaction context already exists, this is used. If no, a new transaction is created. If no new transaction exists, the container starts a new transaction, if a transaction exists, bean uses this transaction.
RequiresNew:
The container creates a new transaction before each method on the bean is called, and submits the transaction before the return. When the bean method is called, new transactions are always started. If the transaction already exists, the transaction is suspended until the new transaction is completed.
NotSupported:
Bean runs outside the transaction context. The existing transaction is suspended during the method call. Bean cannot be called within the transaction. Hangs an existing transaction until the method called in the bean is completed.
Supports:
If the transaction context exists, the method call uses the current transaction context. If it does not exist, no new transaction context is created. The container does not start new transactions. If the transaction already exists, bean will be included in the transaction.
NOTE: With this attribute, beans can run without transactions.
Mandatory:
The transaction context is required for method calling. If not, an exception is thrown. Active transactions must already exist. If no transaction exists, javax. ejb. TransactionRequiredException is thrown.
Never:
The transaction context does not exist for method calls. If yes, an exception is thrown. Bean must always run in different transactions at the same time. If a transaction exists, java. rmi. RemoteException is thrown.

Transaction properties-transaction Propagation

V. transaction isolation level objective: to effectively ensure the correctness of Concurrent Data Reading in database operations, the transaction isolation level is proposed.
Problem:
Lost update)
Both transactions update a row of data at the same time, but the second transaction fails to exit, resulting in invalid modification to both data. This is because the system does not execute any lock operations, so concurrent transactions are not isolated.
Dirty read (Dirty Reads)
A transaction starts to read a row of data, but another transaction has updated the data but cannot be committed in time. This is quite dangerous, because it is very likely that all operations are rolled back.
Non-repeatable Reads)
A transaction reads data from the same row twice but returns different results. It includes the following situations:
(1) After transaction T1 reads a data, transaction T2 modifies it. When transaction T1 reads the data again, it gets a different value from the previous one.
(2) Phantom Reads: The transaction performs two queries during the operation, the results of the second query contain data not found in the first query or missing data in the first query (the SQL statements for the two queries are not required to be the same here ). This is because another transaction inserts data during the two queries.


Unauthorized access to ISOLATION_READ_UNCOMMITED
Dirty reads are allowed, but update loss is not allowed. If a transaction has started writing data, the write operation on the other data is not allowed at the same time, but other transactions are allowed to read this row of data. This isolation level can be achieved through the exclusive write lock.
Authorized to read ISOLATION_READ_COMMITTED
Repeated reads are allowed, but dirty reads are not allowed. This can be achieved through "instant shared read lock" and "exclusive write lock. Transactions that read data allow other transactions to continue to access this row of data, but uncommitted write transactions will prohibit other transactions from accessing this row.
Read ISOLATION_REPEATABLE_READ repeatedly
Duplicate and dirty reading are prohibited, but phantom data may sometimes appear. This can be achieved through the "shared read lock" and "exclusive write lock. The transaction that reads data will prohibit the write transaction (but allow the read transaction), and the write transaction will prohibit any other transactions.
Serialize ISOLATION_SERIALIZABLE
This constant indicates dirty reading. Non-duplicate reading and non-real reading are prohibited.
This level includes blocking on TRANSACTION_REPEATABLE_READ and preventing a transaction from reading all Row Records under WHERE conditions. The second transaction inserts a row under WHERE conditions, then, the previous transaction reads data repeatedly under the same conditions. This is an unauthentic row record.
ISOLATION_DEFAULT (Spring)
The default isolation level is related to a specific database. The default isolation level is adopted for a specific database. Different databases are different.


Transaction isolation policy
Weblogic:
Weblogic-ejb-jar.xml
...
<Transaction-isolation>
<Isolation-level> TransactionSerializable </isolation-level>
<Method>
<Ejb-name> TradingService </ejb-name>
<Method-inf> Remote </method-inf>
<Method-name> placeTrade </method-name>
</Method>
</Transaction-isolation>


Spring:
...
<Bean id = "tradingService" class = "org. springframework. transaction. interceptor. TransactionProxyFactoryBean">
<Property name = "transactionManager"> <ref bean = "transactionManager"/> </property>
<Property name = "target"> <ref local = "tradingService Target"/> </property>
<Property name = "transactionAttributes">
<Props>
<Prop key = "insert *"> PROPAGATION_REQUIRED, ISOLATION_SERIALIZABLE </prop>
</Props>
</Property>
</Bean>


Vi. Local Transaction Model of Transaction type: Local Transaction Model
Custom Transaction Model: Programmatic Transaction Model
Declarative Transaction Model: Declarative Transaction Model
VII. distributed transactions multiple data sources
Two-segment submission Protocol
Step 1: The Transaction Controller asks the resource managers if they are ready for submission;
Step 2: If all resource managers are ready for submission, the Transaction Manager requires all to be submitted.

Spring transaction processing
1. Declarative Transaction Management
2. Programmatic Transaction Management


Spring declarative transactions do not provide transaction context propagation across remote calls provided by high-end application servers. If you need these features, we recommend that you use EJB. However, do not use these features easily. Because we usually do not want transactions to be called remotely.


Transaction Processing in Spring-declarative Transaction Management
Transaction attributes
PROPAGATION_REQUIRED
PROPAGATION_SUPPORTS
PROPAGATION_MANDATORY
PROPAGATION_REQUIRES_NEW
PROPAGATION_NOT_SUPPORTED
PROPAGATION_NEVER
PROPAGATION_NESTED if an active transaction exists, it runs in a nested transaction. If no active transaction exists, it is executed according to the TransactionDefinition. PROPAGATION_REQUIRED attribute. An important concept of nested transactions is that the inner transaction depends on the outer transaction. When an outer transaction fails, the action performed by the internal transaction is rolled back. The failure of the internal transaction does not cause the rollback of the outer transaction.
Isolation level
Whether read-only is read-only. The default value is false.
Most Spring users choose declarative transaction management. This is the smallest choice for application code, so it is also best suited to the non-intrusive lightweight container concept.
Java
// The service class that we want to make transactional
@ Transactional
Public class DefaultFooService implements FooService {
Foo getFoo (String fooName );
Foo getFoo (String fooName, String barName );
Void insertFoo (Foo foo );
Void updateFoo (Foo foo );
}
Xml
<Tx: annotation-driven transaction-manager = "txManager"/>
<! -- A PlatformTransactionManager is still required -->
<Bean id = "txManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager">
<! -- (This dependency is defined somewhere else) -->
<Property name = "dataSource" ref = "dataSource"/>
</Bean>




Transaction Processing in Spring-programmed Transaction Management
Use TransactionTemplate (recommended)
Use a PlatformTransactionManager directly


Use TransactionTemplate
Private final TransactionTemplate transactionTemplate;
// Use constructor-injection to supply the PlatformTransactionManager
Public SimpleService (PlatformTransactionManager transactionManager) {Assert. notNull (transactionManager, "The 'transactionmanager' argument must not be null .");
This. transactionTemplate = new TransactionTemplate (transactionManager );
// The transaction settings can be set here explicitly if so desired this. transactionTemplate. setIsolationLevel (TransactionDefinition. ISOLATION_READ_UNCOMMITTED); // you can specify the transaction isolation level.
This. transactionTemplate. setTimeout (30); // transaction timeout
}
...
TransactionTemplate.exe cute (new TransactionCallbackWithoutResult (){
Protected void doInTransactionWithoutResult (TransactionStatus status ){
Try {
UpdateOperation1 ();
UpdateOperation2 ();
} Catch (SomeBusinessExeption ex ){
Status. setRollbackOnly (); // roll back
}
}
});


Use PlatformTransactionManager


DefaultTransactionDefinition def = new DefaultTransactionDefinition ();
// Explicitly setting the transaction name is something that can only be done programmatically
Def. setName ("SomeTxName"); def. setPropagationBehavior (TransactionDefinition. PROPAGATION_REQUIRED );


TransactionStatus status = txManager. getTransaction (def );
Try {
// Execute your business logic here
} Catch (MyException ex ){
TxManager. rollback (status );
Throw ex;
}
TxManager. commit (status );


<Bean id = "txManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager"> <property name = "dataSource" ref = "dataSource"/> </bean>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.