I am using Spring Boot and need to manage Transaction when registering to DB.
It seems that if you add @Transactional annotation to a public method and raise an Exception, it will automatically roll back.
That's why I tried it, but it didn't work at all. I tried changing the settings given to the annotations, but they didn't roll back at all.
After struggling for two or three hours and crawling the ocean on the Web, I saw a divine lighthouse.
https://ameblo.jp/kochablo/entry-11578714824.html
God
It worked with a single blow. Thanks to the pioneer brother. Thank you very much.
However, I wondered what it was like to call it directly. I would like to help someone who is in trouble like a pioneer brother, and I will explain in detail below.
SampleController.java
class SampleController{
@Autowired
private SampleService sampleService;
public String sample(){
sampleService.transactionalInsert();
return "sampleView";
}
}
SampleService.java
class SampleService{
public void transactionalInsert(){
doInsert();
}
@Transactional
public void doInsert(){
//Somehow, processing such as Insert to DB
//Processing to throw RuntimeExeption if it doesn't work
}
}
This shouldn't be the case.
SampleController.java
class SampleController{
@Autowired
private SampleService sampleService;
public String sample(){
sampleService.doInsert();
return "sampleView";
}
}
SampleService.java
class SampleService{
public void transactionalInsert(){
doInsert();
}
@Transactional
public void doInsert(){
//Somehow, processing such as Insert to DB
//Processing to throw RuntimeExeption if it doesn't work
}
}
Did you understand? Anyway, if you call the @Transactional method from the @Autowired class, it's crazy.
Recommended Posts