Rollback on every checked exception, whenever I say @Transactional

前端 未结 4 594
有刺的猬
有刺的猬 2020-12-02 17:04

Since the programmer is forced to catch all checked exception, I to throw checked exception in case of any problem. I would like to rollback on any of those expections. Writ

4条回答
  •  失恋的感觉
    2020-12-02 17:30

    Custom Shortcut Annotations

    I know, that I could create a custom annotation, but that seems unnatural.

    No, this is exactly the use case for a Custom Annotation. Here's a quote from Custom Shortcut Annotations in the Spring Reference:

    If you find you are repeatedly using the same attributes with @Transactional on many different methods, then Spring's meta-annotation support allows you to define custom shortcut annotations for your specific use cases.

    Sample Code

    And here's a sample annotation for your use case:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Transactional(rollbackFor=Exception.class)
    public @interface MyAnnotation {
    }
    

    Now annotate your services and / or methods with @MyAnnotation (you'll think of a better name). This is well-tested functionality that works by default. Why re-invent the wheel?

提交回复
热议问题