Affects: \
I have multiple datasources, each with transactionManager, one of them is JPA. Flow: 1. read from JPA existing entity 2. in new JPA transaction delete this entity. End transaction. 3. read from JPA same entity
If "flow" is started without existing transaction, for steps 1) and 3) is always new EntityManager created with empty cache, so it always hit DB and step 3 returns null as expected.
However if "flow" is wrapped inside transaction from other transactionManager, then behavior changes and step 1 actually keeps PersistenceContext/EntityManager and same is reused in step 3, so cached value is returned.
I have a feeling this is not correct, as i didn't specify PersistenceContextType.EXTENDED anywhere and accoding to documentation default should be TRANSACTION. As there is no JPA transaction, expectation is to not keep persistence context (session).
See TransactionalDemoTest class example project jpa.multiple.tx.demo.zip. Interesting are methods: - write_thenReadOutsideOfTx_thenDeleteInNewTx_readAgainOutsideOfTx - write_thenWrappedInOtherNonJpaTxManagerScope_read_deleteInRequiresNewTx_readAgainInOriginalTx
Comment From: jhoeller
This is by design: Within any Spring-managed transaction boundary, we reuse resources, as long as transaction synchronization is active. This is primarily meant for JTA scenarios where any accessed resource may implicitly participate in the coordinated transaction. However, this is also applied for regular resource transactions where the primary resource is managed by the transaction manager but any number of additional resources may synchronize themselves with such a current transaction.
You can opt out of this through deactivating transaction synchronization on the transaction manager. Or design your interactions so that the transactions are not interleaving to begin with.