批注接口 Tx


@Target({METHOD,TYPE}) public @interface Tx
Jimmer supports compile-time transaction management AOP implementation. If a class or its methods are annotated with Tx, Jimmer's APT/KSP will automatically generate a derived class for it.
  • If an IOC framework is used, its implementation should be an encapsulation of the transaction management within the IOC framework. Taking jimmer-spring-starter as an example, it is the SpringConnectionManager which will be created and enabled automatically.
  • If no IOC framework is used, the class AbstractTxConnectionManager is the lightweight implementation provided by jimmer, please specify the connection manager of sqlClient by ConnectionManager.simpleConnectionManager(DataSource)

User writes code like this:


 @Tx(Propgation.REQUIRED)
 public class BookRepository {

     final JSqlClient sqlClient;

     public BookRepository(JSqlClient sqlClient) {
         this.sqlClient = sqlClient;
     }

     public List<Book> findBooks() {
         ... ...
     }

     @Tx(Propgation.MANDATORY)
     public void saveBook(BookInput input) {
         ... ...
     }
 }
 

After compilation, a derived class will be generated automatically:


 public class BookRepositoryTx extends BookRepository {

     public BookRepository(JSqlClient sqlClient) {
         super(sqlClient);
     }

     @Override
     public List<Book> findBooks() {
         return sqlClient.transaction(Propagation.REQUIRED, () -> {
             return super.findBooks();
         });
     }

     @Override
     public void saveBook(BookInput input) {
         sqlClient.transaction(Propagation.MANDATORY, () -> {
             super.saveBook(input);
             return null;
         });
     }
 }
 

Obviously,

  • If you are not using an IOC framework, you should use the generated class BookRepositoryTx instead of the original class BookRepository
  • If you are using an IOC framework and replace its transaction AOP, you might want the IOC framework to manage the generated class BookRepositoryTx but not the original class BookRepository. To achieve this, you can use TargetAnnotation.
This annotation can be used to decorate both class and method
  • If this annotation decorates a method, that means that method requires transaction AOP
  • If this annotation decorates a class, that means all public methods of that class require transaction AOP and this annotation is default configuration. Of course, each public method can use its own annotation to override this default configuration.

    Only public methods will be affected, non-public methods will never be affected.

另请参阅:
  • 可选元素概要

    可选元素
    修饰符和类型
    可选元素
    说明
     
  • 元素详细资料