前回の内容だとTransactionの扱いが面倒なので、 MethodInterceptorを使って楽をできるようにする。
アノテーションの用意
@MustBeDocumented @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) @Around @Type(TransactionInterceptor::class) annotation class Transactional
MethodInterceptorの用意
@Singleton class TransactionInterceptor( private val domaConfig: DomaConfig ) : MethodInterceptor<Any, Any> { override fun intercept(context: MethodInvocationContext<Any, Any>): Any { val txManager = domaConfig.transactionManager return txManager.required(Supplier { context.proceed() }) } }
利用
あとは、適当な箇所に @Transactional を付与すれば自動的にTransactionを開始してくれる。 アノテーションにオプションを用意すればREQUIRED以外も利用できるようにできる。