Rollback Using @Transactional in Spring with JPA

This short tutorial will teach you how to roll back a database change using @Transactional annotation in your RESTful Web Service built with Spring Boot and JPA.

Rollback with @Transactional Annotation

Sometimes if an error occurs in our RESTful Web Service, we want to roll back the changes made. For changes to be rolled back in case of an error, you will need to annotate a method in your Rest Controller class with @Transactional annotation. You should also add a @Transactional annotation to a Service layer method if you have one.

Add @Transactional annotation to both:

  • a method in the Controller class and,
  • a method in the Service class.

Add @Transactional to a Method in the Controller Class

Let’s look at an example of a Rest Controller class with a method that accepts HTTP Post requests to create a new user. Please notice that this method is annotated with @Transactional annotation. If an error occurs in the below method after the createUser() method was called, a record inserted into a database will be rolled back.

@Transactional
@PostMapping
 public UserRest createUser(@RequestBody UserDetailsRequestModel requestUserDetails) {
   
       ...

      UserDto createdUser = userService.createUser(userDto);
  
      ....

     return returnValue;
 }

Since the above method uses a Service method called createUser(), the method in the service class will also need to be annotated with @Transactional annotation.

Add @Transactional to a Method in the Service Class

To roll back changes made to a database made by a service layer method, annotate the service layer method with a @Transactional annotation like in the example below:

@Override
@Transactional
public UserDto createUser(UserDto userDto) {
     ...

    // Record data into a database
    userEntity = userRepository.save(userEntity);
  
    ...

    return returnValue;
}

Now when we have annotated both the Rest Controller method and the Service layer method with @Transactional annotation, if an error takes place after the save() method was called and a new record was created in a database, the transaction will be rolled back, and the change will be undone.

I hope this short tutorial on how to roll back changes in your RESTful Web Service in case of an error was helpful to you. You might also want to check out other tutorials on building RESTful Web Services with Spring Boot and Spring Data JPA.

Also, if you are interested in learning Spring Framework by watching step-by-step video lessons, look at the below list of video tutorials.


Leave a Reply

Your email address will not be published. Required fields are marked *