Spring + Hibernate manually creating transactions, PROPAGATION_REQUIRED fails. BUG?

You basically don’t use the transaction API as its intended to. The reference documentation is pretty precise about how to use programatic transactions:

PlatformTransactionManager manager = … // obtain a transaction manager (DI)
TransactionTemplate template = new TransactionTemplate(manager);

template.execute(status -> {
  // Code to be execute in a transaction goes here.

The important point to realize here is that if you want to have code participating in a single transaction, that code needs to go inside the callback. That basically means where you actually put this template code depends on how big you want your transaction boundaries be. If you’d like to run an entire request inside a transaction, place this code inside a ServletFilter and invoke FilterChain.doFilter(…). That will basically cause all the code exceuted the to participate in the same transaction.

Only executing the code in the callback makes sure exceptions trigger a rollback correctly, something that your suggested usage of API totally ignores.

The TransactionTemplate can be instantiated using a TransactionDefinition object which basically defines the characteristics of the transaction to be created.

A bit of general advice

That said, without further knowledge about all the helper methods you introduced (What PlatformTransactionManager implementation to you use? What does getRepository().getTransactionManager() do? Why not inject the PlatformTransactionManager into the test directly?) it’s hard to do any further diagnosis.

If you run into behavior that seems broken at a quick glance, make sure you reduce your code to the essentials and make sure you follow the recommendations of the reference docs. In 90% of the cases the perceived “bug” is just a mistake in using things, often buried in layers of indirection.

If you still think you found a bug, ask in a single canonical place first. If you don’t get an answer in relatively short time, think about whether you might be able to improve the question (reduce the code to it’s essentials etc.). Poorly asked (vage, verbose) questions usually don’t create incentives to answer.

Don’t copy & paste cross-posts into multiple locations. That usually just causes frustration amongst the people you’re actually trying to get help from, as they have to hunt down all of the places you posted to – time, they could’ve used to actually help you.

StackOverflow is a great start usually. If the (mis)behavior can really be confirmed being a bug, a ticket can still be created. Alternatively, create a ticket (and then a ticket only) in the first place but be even more prepared to be required to prepare an executable test case, be precise and – most of all – have read the reference documentation :).

Leave a Comment