【问题标题】:Correlate jOOQ transaction & record listeners关联 jOOQ 事务和记录侦听器
【发布时间】:2021-03-01 14:41:51
【问题描述】:

有没有办法关联 jOOQ 事务和记录侦听器?

一旦将记录添加到某个表中,我需要触发某些操作。 RecordListener#insertEnd 是正确的钩子,但据我所知,这并不能保证确实插入了记录。在调用insertEnd() 后,事务可能仍会回滚 - 或者对一个表的插入可能是一批插入的一部分,也会影响其他表。

另一方面,如果我实现了TransactionListener#comitEnd,我无法确定哪些 记录实际插入到了哪里。 TransactionContext 没有此信息。

【问题讨论】:

    标签: java sql jooq


    【解决方案1】:

    您可以通过访问为此目的而创建的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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2018-09-04
      相关资源
      最近更新 更多