EN
Spring Boot 2.x - commit and rollback transaction manually
4
points
In this short article, we would like to show how to commit and rollback transactions manually in Spring Boot in Java.
Quick solution:
- access transaction manager with
@Autowired
annotation, - create transaction with
getTransation()
method, - commit on success with
commit()
method, - rollback on faliture with
rollback()
method.
Practical example:
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
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 {
@Autowired
private PlatformTransactionManager transactionManager;
@RequestMapping("/path/to/api")
@ResponseBody
public String executeSomeApi() {
TransactionStatus transaction = this.transactionManager.getTransaction(null);
try {
// some code here ...
this.transactionManager.commit(transaction);
return "Success!";
} catch (Throwable ex) {
this.transactionManager.rollback(transaction);
return "Error!";
}
}
}
More complicated example
In this section, the presented example shows how to rollback transactions on fail in different cases.
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
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 {
@Autowired
private PlatformTransactionManager transactionManager;
@RequestMapping(
value = "/path/to/api",
method = RequestMethod.GET,
produces = MediaType.TEXT_PLAIN_VALUE
)
@ResponseBody
public String executeSomeApi() {
TransactionStatus transaction = this.transactionManager.getTransaction(null);
try {
// some code here ...
// if (operationError) {
// this.transactionManager.rollback(transaction);
// return "Error!";
// }
// some code here ...
this.transactionManager.commit(transaction);
return "Success!";
} catch (Throwable ex) {
this.transactionManager.rollback(transaction);
return "Error!";
}
}
}