Spring @Transactional not working with promises

classic Classic list List threaded Threaded
2 messages Options
Tom
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Spring @Transactional not working with promises

Tom
Hi,

I'm developing a Ratpack app and using Spring Boot/JOOQ for the persistence layer.

I'm trying to add transactional support to the service layer. This works fine for a traditional synchronous interface, for example:

    // Service

    @Transactional(readOnly = false, rollbackFor = Exception)
    User test() {
        repo.test()
    }

   // Repo

   @Override
    User test() {
        context.update(MEMBER).set(MEMBER.URL, 'TEST').where(MEMBER.ID.eq(1)).execute()
        new User()
    }

However, it doesn't work when I switch to using promises:

  // Service

  @Transactional(readOnly = false, rollbackFor = Exception)
    Promise<User> test() {
        repo.test()
    }

  // Repo

 @Override
    Promise<User> test() {
        Blocking.op {
            context.update(MEMBER).set(MEMBER.URL, 'TEST').where(MEMBER.ID.eq(1)).execute()
        }.map {
            new User()
        }
    }

Any help would be much appreciated as I'd rather no have to perform manual rollbacks on errors.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Spring @Transactional not working with promises

Tegi
Hello,

Spring wraps the annotated method around with transaction handling code. This means that it starts (or joins) a transaction before your method, and commits (or continues) it after the method returns.
When you're not using a promise, the database access happens inside your method. On the other hand, using a promise your method only defines how the database access should happen. Your method does not execute any of it, it gets executed by some other mechanism (I'm not sure about the Ratpack particulars).
This means that the transaction happens around the definition of the computation, and not the execution of it.
In general: Don't expect Spring annotation based transactions to work with asynchronous frameworks.
This whole concept is hard to grasp the first time, but I hope I've helped.
Loading...