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.

Spring @Transactional Explained

251 views

Published on

Backing slides for the mini-talk requested by the audience about how Spring @Transactional actually works. (Extract from my Spring Framework Training). See www.victorrentea.ro/#spring for more details about the full training

Published in: Software
  • Be the first to comment

Spring @Transactional Explained

  1. 1. VictorRentea.ro @Transactional 1 JPA – Runtime @Transactional(propagation = Propagation.SUPPORTS) public class EmployeeService { public void getEmployee(long employeeId) { ... } @Transactional(propagation = Propagation.MANDATORY) public void createEmployee(Employee employee) { ... } } Works via an AOP Proxy wrapping the EmployeeService
  2. 2. VictorRentea.ro @Transactional  Life 2 JPA – Runtime Account Service Account Repo Transfer Service payEnelBill() getAccount SUPPORTS payBill() COMMIT MANDATORY @Transactional(propagation = REQUIRED) Persistence Context @PersistenceContext private EntityManager em; Inject an EntityManager proxy em.find(...) em.find(...)
  3. 3. VictorRentea.ro3 JPA – Runtime class B { @Transactional(propag=???) public void b() { ... } } @Autowired private B b; public void a() { b.b(); } How does it work? proxy @Transactional I can do more stuff before calling the real b()
  4. 4. VictorRentea.ro Propagation 4 JPA – Runtime supports required=default requires new mandatory not supported never nested ! class B { @Transactional(propag=???) public void b() { ... } } @Autowired private B b; public void a() { b.b(); } existing Tx no Tx a b a b pause Tx ex ex Caller Tx New Tx No Tx @Transactional on ex, only this is lost (SAVEPOINT)
  5. 5. VictorRentea.ro PC2 REQUIRES_NEW @Transactional  Life 5 JPA – Runtime Account Service Account Repo Transfer Service payEnelBill() getAccount SUPPORTS payBill() ROLLBACK MANDATORY REQUIRED Persistence Context em.find(...) Error Repo @PersistenceContext private EntityManager em; try { } catch (e) { } REQUIRED em.persist(error) tx.setRollbackOnly() persistError() COMMIT Ex
  6. 6. VictorRentea.ro Throw a RuntimeException from a method, if: - The method allows the Tx to enter, and - The method is aspected by TransactionInterception When is a method Tx-aspected? - If there is any @Transactional in that class ? How do you kill a @Tx ? 6 JPA – Runtime This one actually kills the Tx Can be customized: @Transactional(rollbackFor=…, noRollbackFor=…)

×