Reputation:
I have a spring boot application where, I have endpoints to save Primary and Secondary Users into database.
Here for some primary users they have "loginId" and "name" of Secondary Users.
The problem is:
How can I rollback all the data's if an exception occurred (the data that saved in the saveSecondary method), In this case?
Thanks
@RestController
@Transactional
public class HomeController {
@Autowired
private PrimaryRepository primaryRepo;
@Autowired
private SecondaryRepository secondaryRepo;
@PostMapping("/save/primary")
public void savePrimary(@RequestBody Primary primaryUser) throws FileNotFoundException {
try {
if(primaryUser.hasSecondaryUser()){
SecondaryUser obj = new SecondaryUser();
obj.setName = primaryUser.getSecondaryUserName();
obj.setLoginId = primaryUser.getLoginId();
obj.hasPrimaryUser = true;
saveSecondary(obj);
}
/* If some exception occurs here how to rollback the saveSecondary(obj); --> data also*/
FileReader file = new FileReader("property.txt");
primaryRepo.save(primaryUser);
} catch (Exception e) {
System.out.println("Error occurred :" + e.getMessage());
}
}
@PostMapping("/save/secondary")
public void saveSecondary(@RequestBody SecondaryUser obj) throws Exception {
secondaryRepo.save(obj);
}
Upvotes: 0
Views: 115
Reputation: 1201
You should move this code to another method in your primaryService
and use @Transactional(rollbackFor=Exception.class)
annotation above the method.
the @Transactional
annotation is used to rollback in case of an exception with saving to the database, and when you set rollbackFor=Exception.class
it will rollback for any given exception in the method.
so you code should look like this:
primaryService
@Transactional(rollbackFor=Exception.class)
public void saveBoth(primaryUser) throws Exception {
if(primaryUser.hasSecondaryUser()){
SecondaryUser obj = new SecondaryUser();
obj.setName = primaryUser.getSecondaryUserName();
obj.setLoginId = primaryUser.getLoginId();
obj.hasPrimaryUser = true;
saveSecondary(obj);
}
FileReader file = new FileReader("property.txt");
this.save(primaryUser);
}
@Transactional
annotation to workHomeController
@PostMapping("/save/primary")
public void savePrimary(@RequestBody Primary primaryUser) {
try {
primaryService.saveBoth(primaryUser);
} catch (Exception e) {
System.out.println("Error occurred :" + e.getMessage());
}
}
Upvotes: 1