Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

[Java eeconf 2016] spring jta principles of work with transactions. Dmytro Sokolov

1,030 views

Published on

cover following topics:

the internal structure of Spring JTA;
possible configuration with Spring AOP;
all features of the framework for handling transactions;
the types of sources of transactions and how to work with them;
distributed transactions with multiple data sources;
integration with Spring JdbcTemplate, Hibernate, JMS.

  • Be the first to comment

[Java eeconf 2016] spring jta principles of work with transactions. Dmytro Sokolov

  1. 1. Spring JTA: Principles of work with transactions .com
  2. 2. .com Dmytro Sokolov ▷10 years Java Developer ▷3 years Trainer & Mentor ▷Java Trainer / Lead Software Engineer ▷Full-stack experience ▷Project: BecomeJavaSenior.com ▷email: becomejavasenior@gmail.com Hello! .com
  3. 3. .com.com
  4. 4. .com Agenda ▷The internal structure of Spring JTA; ▷Possible configuration with Spring AOP; ▷Transaction Concepts ▷Benefits of Spring JTA ▷Best Practices and pitfalls
  5. 5. .com The internal structure of Spring JTA
  6. 6. .com Transaction What transaction models do you know?
  7. 7. .com Local Transaction model with JDBC connection.setAutoCommit(false); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { connection.rollback();
  8. 8. .com Programmatic Transaction model with JPA UserTransaction utx = entityManager.getTransaction(); try { utx.begin(); businessLogic(); utx.commit(); } catch(Exception ex) { utx.rollback(); throw ex;
  9. 9. .com Declarative Transaction model with Spring ?
  10. 10. .com
  11. 11. .com @Transactional
  12. 12. .com @Transactional
  13. 13. .com @Transactional What does do ?
  14. 14. .com Bean registration What does do ? 1.Execute AopAutoProxyConfigurer.configureAutoProxyCreator()
  15. 15. .com Bean registration What does do ? 2. Which create TransactionInterceptor
  16. 16. .com Bean registration What does do ? 3. Search declared TransactionManager and attached it to TransactionInterceptor
  17. 17. .com Bean registration What does do ? 4. Register TransactionInterceptor bean in Spring Context
  18. 18. .com @Transactional parsing How @Transactional annotation is parsed during runtime by Spring?
  19. 19. .com @Transactional parsing How @Transactional annotation is parsed during runtime by Spring? Registers the SpringTransactionAnnotationParser as default parser for the @Transactional annotation
  20. 20. .com Transactional interceptor invocation What does TransactionInterceptor do?
  21. 21. .com Transactional interceptor invocation What does TransactionInterceptor do? 1.Retrieves the transaction attributes txAttr = getTransactionAttributeSource(). getTransactionAttribute(invocation.getMethod(), targetClass);
  22. 22. .com Transactional interceptor invocation What does TransactionInterceptor do? 2. Gets the transaction manager from the Spring context and transaction attributes PlatformTransactionManager tm = determineTransactionManager(txAttr);
  23. 23. .com Transactional interceptor invocation What does TransactionInterceptor do? 4. A transaction is created by the underlying entity manager TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
  24. 24. .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;
  25. 25. .com Transactional interceptor invocation What does TransactionInterceptor do? 5. The transaction is committed commitTransactionAfterReturning(txInfo);
  26. 26. .com Transactional interceptor invocation What does AbstractPlatformTransactionManage r do?
  27. 27. .com TransactionManager invocation What does AbstractPlatformTransactionManager do? Delegates the creation and the start of the transaction itself to the underlying JpaTransactionManager.
  28. 28. .com TransactionManager invocation What does JpaTransactionManager do?
  29. 29. .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());
  30. 30. .com TransactionManager invocation What does JpaTransactionManager do? 2. Retrieves the dataSource declared for this transaction manager ConnectionHolder conHolder = TransactionSynchronizationManager.getResource( getDataSource());
  31. 31. .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(...)
  32. 32. .com TransactionManager invocation What does JpaTransactionManager do? 4. Registers the current JDBC connection to the TransactionSynchronizationManager ThreadLocal map TransactionSynchronizationManager.bindResource(ge tDataSource(), conHolder);
  33. 33. .com TransactionManager invocation And finally execute: beginTransaction(entityManager, definition); prepareTransaction(entityManager, ...); commitTransactionAfterReturning(...);
  34. 34. .com Possible configuration with Spring AOP DEMO
  35. 35. .com Transaction Concepts
  36. 36. .com X/Open XA standard XA(eXtended Architecture) is how one/multiple resources is integrating with a transaction manager
  37. 37. .com X/Open XA standard supports both the 1- phase commit protocol and the 2-phase commit protocol.
  38. 38. .com Managing single or multiple resources single resource - 1-phase commit multiple resources - 2-phase commit
  39. 39. .com X/Open XA standard Resources that support the XA standard expose a special object, the XA switch Interface javax.transaction.xa.XAResource
  40. 40. .com Transactions and threading Transactions are thread-specific
  41. 41. .com Transaction context At a minimum, the transaction context contains a unique transaction identifier. Depends on the relevant transaction manager implementation
  42. 42. .com Transaction manager The 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
  43. 43. .com Transaction managers in Spring
  44. 44. .com Transaction managers in Spring + JdoTransactionManager JmsTransactionManager, WebLogicJtaTransactionManager WebSphereUowTransactionManage r
  45. 45. .com Transaction managers in Spring PlatformTransactionManager Interface getTransaction(TransactionDefinition definition) void commit(TransactionStatus status) void rollback(TransactionStatus status)
  46. 46. .com Transaction managers in Spring TransactionDefinition interface isolation level and the propagation policy
  47. 47. .com Transaction managers in Spring TransactionStatus interface check the status of the current transaction
  48. 48. .com Transaction managers in Spring AbstractPlatformTransactionManager class ▷determines transaction; ▷applies propagation behavior; ▷suspends and resumes transactions; ▷checks the rollback-only flag on commit;
  49. 49. .com Local transaction managers in Spring can coordinate transactions over a single resource only typically embedded in the resource itself
  50. 50. .com Local transaction managers in Spring JDBC Spring Transaction Manager JDBC resource Oracle DB built-in Transaction Manager BEGIN, COMMIT, ROLLBACK native Oracle API
  51. 51. .com Local transaction managers in Spring JMS Spring Transaction Manager (facade) Resource instance of the JMS queues topics
  52. 52. .com Spring Transaction Architecture Standalone Spring container
  53. 53. .com Global transaction managers in Spring Global transaction manager is TP monitor (transaction processing monitor ) ▷implements the 2-phase commit ▷coordinate multiple XA resources
  54. 54. .com Global transaction managers in Spring JtaTransactionManager OC4JJtaTransactionManagner WebLogicJtaTransactionManager WebSphereUowTransactionManager
  55. 55. .com Global transactions with JTA
  56. 56. .com Spring Transaction Architecture J2EE container deployment
  57. 57. .com Global transactions with JTA To manage custom global JDBC and JMS transaction see opensource Atomikos or Bitronix
  58. 58. .com Distributed transaction managers in Spring Distributed transaction managers does not supported from box Outside the scope of the Spring framework.
  59. 59. .com Benefits of Spring JTA vs EJB
  60. 60. .com Spring JTA benefits Work with ▷JTA transactions ▷JDBC ▷JPA ▷Hibernate ▷JDO ▷JMS
  61. 61. .com Spring JTA benefits AOP declarative transaction management
  62. 62. .com Spring JTA benefits Programmatic transaction management
  63. 63. .com Spring JTA benefits Offers declarative rollback rules
  64. 64. .com Spring JTA benefits Customize transactional behavior ▷insert custom behavior in the case of transaction rollback ▷add arbitrary advice ▷rollback the transaction automatically on an application exception
  65. 65. .com Spring JTA benefits Do not depends from Application Server
  66. 66. .com Spring JTA benefits No needs transaction-related JNDI lookups
  67. 67. .com Best Practices and pitfalls
  68. 68. .com Declarative definition has logic
  69. 69. .com Different behavior for diff Tx Managers @Transactional(readOnly = true, propagation=Propagation.REQUIRED) public long insertTrade(TradeData trade) throws Exception { //JDBC code... }
  70. 70. .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(); }
  71. 71. .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
  72. 72. .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.REQUIRED Do you really need transaction for reading?
  73. 73. .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); }
  74. 74. .com Be aware of Propagation behavior Or even no transaction public TradeData getTrade(long tradeId) throws Exception { return em.find(TradeData.class, tradeId);
  75. 75. .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?
  76. 76. .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?
  77. 77. .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; } }
  78. 78. .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?
  79. 79. Thanks! Any questions? You can find me at: becomejavasenior@gmail.com .com

×