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:
xxxxxxxxxx
1
package com.example;
2
3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.http.MediaType;
5
import org.springframework.stereotype.Controller;
6
import org.springframework.transaction.PlatformTransactionManager;
7
import org.springframework.transaction.TransactionStatus;
8
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
9
import org.springframework.web.bind.annotation.RequestMapping;
10
import org.springframework.web.bind.annotation.RequestMethod;
11
import org.springframework.web.bind.annotation.ResponseBody;
12
13
14
public class ExampleController {
15
16
17
private PlatformTransactionManager transactionManager;
18
19
"/path/to/api") (
20
21
public String executeSomeApi() {
22
TransactionStatus transaction = this.transactionManager.getTransaction(null);
23
try {
24
// some code here ...
25
26
this.transactionManager.commit(transaction);
27
return "Success!";
28
} catch (Throwable ex) {
29
this.transactionManager.rollback(transaction);
30
return "Error!";
31
}
32
}
33
}
In this section, the presented example shows how to rollback transactions on fail in different cases.
xxxxxxxxxx
1
package com.example;
2
3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.http.MediaType;
5
import org.springframework.stereotype.Controller;
6
import org.springframework.transaction.PlatformTransactionManager;
7
import org.springframework.transaction.TransactionStatus;
8
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
9
import org.springframework.web.bind.annotation.RequestMapping;
10
import org.springframework.web.bind.annotation.RequestMethod;
11
import org.springframework.web.bind.annotation.ResponseBody;
12
13
14
public class ExampleController {
15
16
17
private PlatformTransactionManager transactionManager;
18
19
(
20
value = "/path/to/api",
21
method = RequestMethod.GET,
22
produces = MediaType.TEXT_PLAIN_VALUE
23
)
24
25
public String executeSomeApi() {
26
TransactionStatus transaction = this.transactionManager.getTransaction(null);
27
try {
28
// some code here ...
29
30
// if (operationError) {
31
// this.transactionManager.rollback(transaction);
32
// return "Error!";
33
// }
34
35
// some code here ...
36
37
this.transactionManager.commit(transaction);
38
return "Success!";
39
} catch (Throwable ex) {
40
this.transactionManager.rollback(transaction);
41
return "Error!";
42
}
43
}
44
}