user15195885
user15195885

Reputation:

Customize the commit functionality in Spring JPA Hibernate

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

Answers (1)

Noy Gafni
Noy Gafni

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);
}
  • note that you must use public method for the @Transactional annotation to work

HomeController

@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

Related Questions