[Java eeconf 2016] spring jta principles of work with transactions. Dmytro Sokolov
-
Upload
dmytro-sokolov -
Category
Presentations & Public Speaking
-
view
501 -
download
0
Transcript of [Java eeconf 2016] spring jta principles of work with transactions. Dmytro Sokolov
Spring JTA: Principles of work with transactions.com
.com
Dmytro Sokolov▷10 years Java Developer▷3 years Trainer & Mentor▷Java Trainer / Lead Software Engineer
▷Full-stack experience▷Project: BecomeJavaSenior.com▷email: [email protected]
Hello!
.com
.com
Agenda▷The internal structure of Spring JTA;
▷Possible configuration with Spring AOP;
▷Transaction Concepts
▷Benefits of Spring JTA
▷Best Practices and pitfalls
.com
Local Transaction model with JDBC
connection.setAutoCommit(false);
preparedStatement.executeUpdate();
connection.commit();
} catch (SQLException e) {
connection.rollback();
.com
Programmatic Transaction model with JPA
UserTransaction utx =
entityManager.getTransaction();
try {
utx.begin();
businessLogic();
utx.commit();
} catch(Exception ex) {
utx.rollback();
throw ex;
.com
Bean registrationWhat does
do ?
1.ExecuteAopAutoProxyConfigurer.configureAutoProxyCreator()
.com
Bean registrationWhat does
do ?
2. Which createTransactionInterceptor
.com
Bean registrationWhat does
do ?
3. Search declared TransactionManager and attached it to TransactionInterceptor
.com
Bean registrationWhat does
do ?
4. Register TransactionInterceptor bean in Spring Context
.com
@Transactional parsingHow @Transactional annotation is parsed during runtime by Spring?
.com
@Transactional parsingHow @Transactional annotation is parsed during runtime by Spring?
Registers the SpringTransactionAnnotationParser as default parser for the @Transactional annotation
.com
Transactional interceptor invocation
What does TransactionInterceptor do?
.com
Transactional interceptor invocation
What does TransactionInterceptor do?
1.Retrieves the transaction attributes
txAttr = getTransactionAttributeSource().
getTransactionAttribute(invocation.getMetho
d(), targetClass);
.com
Transactional interceptor invocation
What does TransactionInterceptor do?
2. Gets the transaction manager from the Spring context and transaction attributes
PlatformTransactionManager tm =
determineTransactionManager(txAttr);
.com
Transactional interceptor invocation
What does TransactionInterceptor do?
4. A transaction is created by the underlying entity managerTransactionInfo txInfo =
createTransactionIfNecessary(tm, txAttr,
joinpointIdentification);
.com
Transactional interceptor invocation
What does TransactionInterceptor do?
5. The target method is invoked retVal = invocation.proceed();
} catch (Throwable ex)
{ completeTransactionAfterThrowing(txInfo,
ex);
throw ex;
.com
Transactional interceptor invocation
What does TransactionInterceptor do?
5. The transaction is committed commitTransactionAfterReturning(txInfo);
.com
Transactional interceptor invocation
What does AbstractPlatformTransactionManager do?
.com
TransactionManager invocation
What does AbstractPlatformTransactionManager do?
Delegates the creation and the start of the transaction itself to the underlying JpaTransactionManager.
.com
TransactionManager invocation
What does JpaTransactionManager do?
1. Tries to look an existing entity manager using the entity manager factory
EntityManagerHolder emHolder =
TransactionSynchronizationManager.getResource
( getEntityManagerFactory());
.com
TransactionManager invocation
What does JpaTransactionManager do?
2. Retrieves the dataSource declared for this transaction manager
ConnectionHolder conHolder =
TransactionSynchronizationManager.getResource
( getDataSource());
.com
TransactionManager invocation
What does JpaTransactionManager do?
3. Delegates the creation of a new JDBC transaction to the underlying JPA Dialect
Object transactionData =
getJpaDialect().beginTransaction(...)
.com
TransactionManager invocation
What does JpaTransactionManager do?
4. Registers the current JDBC connection to the TransactionSynchronizationManager ThreadLocal map
TransactionSynchronizationManager.bindResour
ce(getDataSource(), conHolder);
.com
TransactionManager invocation
And finally execute:
beginTransaction(entityManager, definition);
prepareTransaction(entityManager, ...);
commitTransactionAfterReturning(...);
.com
X/Open XA standardXA (eXtended Architecture) ishow one/multiple resources is integrating with a transaction manager
.com
X/Open XA standardsupports both the 1-phase commit protocol and the 2-phase commit protocol.
.com
Managing single or multiple resources
single resource - 1-phase commit multiple resources - 2-phase commit
.com
X/Open XA standardResources that support the XA standard expose a special object, the XA switch Interface javax.transaction.xa.XAResource
.com
Transaction contextAt a minimum, the transaction context contains a unique transaction identifier.
Depends on the relevant transaction manager implementation
.com
Transaction managerThe features determine the quality of service of a transaction manager:▷Support for multiple resources
▷Distributed transactions▷Transaction monitoring▷Recovery from failure▷Support for suspend/resume and attach/detach
.com
Transaction managers in Spring
+ JdoTransactionManagerJmsTransactionManager,WebLogicJtaTransactionManagerWebSphereUowTransactionManager
.com
Transaction managers in Spring
PlatformTransactionManager Interface
getTransaction(TransactionDefinition definition)void commit(TransactionStatus status) void rollback(TransactionStatus status)
.com
Transaction managers in Spring
TransactionDefinition interface
isolation level and the propagation policy
.com
Transaction managers in Spring
TransactionStatus interface
check the status of the current transaction
.com
Transaction managers in Spring
AbstractPlatformTransactionManager class
▷determines transaction;▷applies propagation behavior;▷suspends and resumes transactions;▷checks the rollback-only flag on commit;
.com
Local transaction managers in Spring
can coordinate transactions over a single resource only
typically embedded in the resource itself
.com
Local transaction managers in Spring JDBC
Spring Transaction ManagerJDBC resource
Oracle DB
built-in TransactionManager
BEGIN, COMMIT, ROLLBACKnative Oracle API
.com
Local transaction managers in Spring JMS
Spring Transaction Manager(facade)Resource
instance of the JMS queues
topics
.com
Global transaction managers in Spring
Global transaction manager is TP monitor(transaction processing monitor )
▷implements the 2-phase commit
▷coordinate multiple XA resources
.com
Global transaction managers in Spring
JtaTransactionManagerOC4JJtaTransactionManagnerWebLogicJtaTransactionManagerWebSphereUowTransactionManager
.com
Global transactions with JTA
To manage custom global JDBC and JMS transaction see opensource Atomikos or Bitronix
.com
Distributed transaction managers in Spring
Distributed transaction managers does not supported from boxOutside the scope of the Spring framework.
.com
Spring JTA benefitsWork with ▷JTA transactions▷JDBC ▷JPA▷Hibernate ▷JDO ▷JMS
.com
Spring JTA benefitsCustomize transactional behavior
▷insert custom behavior in the case of transaction rollback
▷add arbitrary advice▷rollback the transaction automatically on an application exception
.com
Different behavior for diff Tx Managers
@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
public long insertTrade(TradeData trade) throws Exception { //JDBC code...}
.com
Different behavior for diff Tx Managers
Not always the same:@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
public long insertTrade(TradeData trade) throws Exception { em.persist(trade); return trade.getTradeId();}
.com
Be aware of Propagation behavior
@Transactional(readOnly = true, propagation=Propagation.SUPPORT)public long insertTrade(TradeData trade) throws Exception { //JDBC code...}
Allows to write data
.com
Be aware of Propagation behavior
@Transactional(readOnly = true)public TradeData getTrade(long tradeId) throws Exception { return em.find(TradeData.class, tradeId);}
Will use Propagation.REQUIREDDo you really need transaction for reading?
.com
Be aware of Propagation behavior
How about
@Transactional(readOnly = true, propagation=Propagation.SUPPORTS)public TradeData getTrade(long tradeId) throws Exception { return em.find(TradeData.class, tradeId);}
.com
Be aware of Propagation behavior
Or even no transaction public TradeData getTrade(long tradeId) throws Exception { return em.find(TradeData.class, tradeId);
.com
Be aware of Propagation behavior
@Transactional(propagation=Propagation.REQUIRES_NEW)public long insertTrade(TradeData trade) throws Exception {...}
@Transactional(propagation=Propagation.REQUIRES_NEW)public void updateAcct(TradeData trade) throws Exception {...}
Do you really need always new Transaction?
.com
Rollback behavior@Transactional(propagation=Propagation.REQUIRED)public TradeData placeTrade(TradeData trade) throws Exception { try { insertTrade(trade); updateAcct(trade); return trade; } catch (Exception up) { //log the error throw up; }Will transaction Rollback in case of throw Exception?
.com
Rollback behavior@Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)public TradeData placeTrade(TradeData trade) throws Exception { try { insertTrade(trade); updateAcct(trade); return trade; } catch (Exception up) { //log the error throw up; }}
.com
Transaction isolation@Transactional(propagation= Propagation.REQUIRED, Isolation = Isolation.REPEATABLE_READ)public long insertTrade(TradeData trade) throws Exception { //JDBC or JPA code...}
Will isolation always be changed?