Spring boot and JPA transaction doesn't work

I'm trying to save many entities atomically by running multiple save methods in a transaction so if any of those fails, all of them will be discarded (rollback). I've tried many things but nothing seems to work fine:

BookingResource.java:

@RestController
public class BookingResource {

    @Autowired
    private ReservationRepository reservationRepository;

    @PostMapping("/booking")
    @Transactional(noRollbackFor=RuntimeException.class)
    public ResponseEntity<BookingResourceResponse> createReservtion(@RequestBody Reservation body) {
        //code...
        try {
            int day = 0;

            do {
                reservationRepository.save(new Reservation(..., day));
            }
            while(day <= LIMIT_VALUE);
            return buildResponse(HttpStatus.CREATED, new BookingResourceResponse(body));
        }
        catch(Exception e) {
            return buildResponse(HttpStatus.CONFLICT, new BookingResourceResponse("Some error here"));
        }
    }

}

ReservationRepository.java:

public interface ReservationRepository extends JpaRepository<Reservation, Long> {

}

Reservation.java:

@Entity
public class Reservation {

    @Id
    @Column(name="reservation_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String uuid;
    private String email;
    private String name;
    @Column(name="last_name")
    private String lastName;
    @Column(unique=true)
    private LocalDate date;
    private LocalDate dateTo;

    public Reservation() {
        //blank
    }

    public Reservation(..., int day) {
        //...
    }
    //... getters and setters
}

And the stacktrace is:

org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755) ~[spring-tx-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714) ~[spring-tx-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:533) ~[spring-tx-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:304) ~[spring-tx-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at com.upgrade.volcano.resources.BookingResource$$EnhancerBySpringCGLIB$$3a7479ff.createReservtion(<generated>) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.4.BUILD-SNAPSHOT.jar:5.1.4.BUILD-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.14.jar:9.0.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.14.jar:9.0.14]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]

So, what is happening here? How can I solve it? I've tried to making the methods public, changing the transaction policy, but nothing works. There's a workaround for it?

Thanks!

1 answer

  • answered 2019-01-11 06:59 Ken Chan

    What is happening here?

    Transaction silently rolled back because it has been marked as rollback-only.

    It happens when an outer @Transactional method calls an inner @Transactional method and both are under same physical TX (e.g. Both are Propagation.REQUIRED which are the default setting). Then , when an inner method throws an exception , it will mark the TX as required rollback. However if the outer method commit the TX , this exception will happen. It is a normal behaviour as designed because the inner method says it want to rollback but outer method says it want to commit which contradict with each other.

    In your case, the inner method that has @Transactional come from JpaRepository#save (This is the current design of Spring data). If exception happens in it and you catch all exceptions in the outer method (i.e BookingResource#createReservtion()), this exception happens.

    Solution

    According to your requirements, you have to re-throw the exception from BookingResource#createReservtion() after you caught the exception. Also need to make sure noRollbackFor in createReservtion() 's @Transactional is not set to the any type which is the same as the rethrown exception in order to signal that you want to rollback rather than commit the outer method , something like :

    @PostMapping("/booking")
    @Transactional
    public ResponseEntity<BookingResourceResponse> createReservtion(@RequestBody Reservation body) {
        //code...
        try {
            int day = 0;
            do {
                reservationRepository.save(new Reservation(..., day));
            }
            while(day <= LIMIT_VALUE);
            return buildResponse(HttpStatus.CREATED, new BookingResourceResponse(body));
        }
        catch(Exception e) {
            throw new AppException(buildResponse(HttpStatus.CONFLICT, new BookingResourceResponse("Some error here")) , e);
        }
    }