Rollback Using @Transactional in Spring with JPA

In this short tutorial, you will learn how to rollback a database change using @Transactional annotation in your RESTful Web Service built with Spring MVC and JPA.

Rollback with @Transactional Annotation

Sometimes if an error takes place in our RESTful Web Service we want to rollback 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: the Controller class and the Service class. 

Add @Transactional to a Method in the Controller Class

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

@Transactional
@PostMapping(
         produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
         consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
 )
 public UserRest createUser(@RequestBody UserDetailsRequestModel requestUserDetails) {
   
       ...

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

     return returnValue;
 }

Since the above method makes use of a Service method called createUser(), this method will also need to be annotated with @Transactional annotation.

Add @Transactional to a Method in the Service Class

To rollback 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 rollback changes in your RESTful Web Service in case of an error, was helpful to you. Check out other tutorials related to building RESTful Web Services with Spring Boot, MVC and Spring Data JPA on this page.

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