Search code examples
javatransactionsjdbctemplatemicronaut

How to use Micronaut with Spring Jdbctemplate and transactions?


Expected Behavior

When using the @Transactional annotation I expect the database operations to fall into a transaction scope and if any step fails the rollback should be done.

Actual Behaviour

In the current scenario, even with an @Transactional annotation, in case of an operation failure, the rollback is not done, causing inconsistency

Steps To Reproduce

  1. In your database apply the DDL script
  2. Perform the following operation on the database to create an account insert into ACCOUNTS (ACCOUNT_NUMBER, BALANCE) values ​​('0000001',0.0)
  3. Run the application and execute the curl below:
curl --location --request POST 'http://localhost:8080/deposit' \
--header 'Content-Type: application/json' \
--data-raw '{
  "accountNumber": "0000001",
  "amount": 999.20
}'

You will see a DataIntegrityViolationException being thrown, this is because the history table has an ill-defined field with a decimal amount(2,2) and the deposit amount does not match, in this case I expected the account balance update to be reversed , however this does not occur.

I saw that there is already an issue about problem #651 that was closed, but the micronaut data documentation suggests that this feature works because in item 10 there is the following text:

In addition to this dependency you will need either spring-orm (for Hibernate) or spring-jdbc (for JDBC) on your classpath to enable support for Spring-based transaction management:

Could you clarify this point please? We are planning to migrate some applications from spring to micronaut and they are all developed with jdbctemplate so the transition would be a lot easier if I could make this point work, maybe I've lost something in the documentation or I'm getting it wrong at some point, thanks for the good work.

Environment Information

Operating System: Windows 11 JDK: Zulu JDK 11.0.12 Maven 3.6.3 Micronaut 2.5.4

Example Application

https://github.com/viniciusxyz/micronaut-transaction-failed

Version

2.5.4


Solution

  • I solved the problem.

    Just replace the dependency:

            <dependency>
                <groupId>io.micronaut.data</groupId>
                <artifactId>micronaut-data-spring</artifactId>
                <scope>compile</scope>
            </dependency>
    

    per:

                <dependency>
                    <groupId>io.micronaut.spring</groupId>
                    <artifactId>micronaut-spring</artifactId>
                    <scope>compile</scope>
                </dependency>