Languages
[Edit]
EN

Spring Boot 2.x - transaction with controller request

5 points
Created by:
Joshua-Heath
685

In this short article, we would like to show how to add transaction to controller request in Spring Boot in Java.

Quick solution: add @Transactional annottation to selected controller method.

 

Practical example

In below example operations are rolled back on any exceptions that occured in the method.

package com.example

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ExampleController {

    @RequestMapping(
            value = "/path/to/api",
            method = RequestMethod.GET,
            produces = MediaType.TEXT_PLAIN_VALUE
    )
    @Transactional
    @ResponseBody
    public String executeSomeApi() {
        // some code here ...

        // if (operationError) {
        //     throw new SomeException("Exception message here ...");  // it rollbacks transaction
        // }

        // some code here ...
        return "Some success response here ...";
    }
}

See also

  1. Spring Boot 2.x - commit and rollback transaction manually 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join