我有使用交易在Kotlin編寫的Jooq代碼,有時我想要一種獨立工作的方法作爲頂級操作,該操作將擁有自己的交易和其他時間希望它能夠在同一事務中與其他方法合成。例如,我有兩個較低級別的函數actionAbc
和actionXyz
,我想將它們組合成不同的更高級別的數據方法,並繼承它們的事務(如果存在),否則將擁有它們自己的事務。如何更輕鬆地在Kotlin中使用Jooq交易
我知道在Spring或其他框架中有可以添加的驗證「需要事務」或「創建事務如果沒有」類型功能的註釋。但是,如何在不使用這些庫的情況下對Jooq + Kotlin執行相同操作?
我想到的最接近的是將事務作爲可選參數傳遞,如果缺失,則默認爲新事務。但是如果有人忘記了通過交易,那麼使用新的頂級和不相關的交易的細微失敗,我不希望這樣。
fun tx(ctx: DSLContext = rootContext, codeBlock: DSLContext.() -> Unit): Unit {
ctx.transaction { cfg ->
DSL.using(cfg).codeBlock()
}
}
}
// and used as:
fun actionAbc(parm1: String, parm2: Int, ctx: DSLContext = rootContext) {
tx(ctx) { ... }
}
fun actionXyz(parm: Date, ctx: DSLContext = rootContext) {
tx(ctx) { ... }
}
// composed:
fun higherLevelAction(parm1: String, parm2: Date) {
tx {
actionAbc(parm1, 45, this) // if you forget `this` you are doing the wrong thing
actionXyz(parm2, this)
tx(this) {
// nested transaction, also dangerous if forgetting `this` parameter
}
}
}
我如何做到這一點更自然,少危險?
注:這個問題是故意寫的,並回答了作者(Self-Answered Questions),使解答常見科特林主題存在於SO。