EN
Spring Boot 2.x - transaction with controller request
5
points
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 ...";
}
}