jooq事务和记录侦听器

1cosmwyk  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(332)

有没有办法关联jooq事务和记录侦听器?
一旦记录添加到某个表中,我就需要触发某些操作。 RecordListener#insertEnd 是正确的钩,但据我所知,这并不保证记录是真的插入。事务仍可能在之后回滚 insertEnd() 或者对一个表的插入可能是也影响其他表的一批插入的一部分。
另一方面,如果我 TransactionListener#comitEnd 我搞不清楚到底是哪条记录插入的。 TransactionContext 没有这个信息。

bnl4lu3b

bnl4lu3b1#

您可以通过访问 Configuration.data() 为此目的而创建的属性。考虑以下两个听众:

class RL extends DefaultRecordListener {
    @Override
    public void insertEnd(RecordContext ctx) {
        // Put some property into the data map
        ctx.configuration().data("x", "y");
    }
}

class TL extends DefaultTransactionListener {
    String x;

    @Override
    public void commitEnd(TransactionContext ctx) {
        // Retrieve the property again
        x = (String) ctx.configuration().data("x");
    }
}

然后可以如下使用:

RL rl = new RL();
TL tl = new TL();

ctx.configuration()
   .derive(rl)
   .derive(tl)
   .dsl()
   .transaction(c -> {
        assertNull(c.data("x"));

        TRecord t = c.dsl().newRecord(T);
        t.setA("a");
        t.setB("b");

        // insertEnd() triggered here
        assertEquals(1, t.insert());
        assertEquals("y", c.data("x"));

    // commitEnd() triggered here
    });

// Since the transaction creates a nested, derived scope, you don't see these things
// from the outside of the transaction in your possibly global Configuration
assertNull(ctx.data("x"));
assertNull(ctx.configuration().data("x"));
assertEquals("y", tl.x);

相关问题