java - Correlate jOOQ transaction & record listeners
问题描述
Is there a way to correlate jOOQ transaction & record listeners?
I need to trigger certain actions once records where added to a certain table. RecordListener#insertEnd
is the proper hook for that but to my knowledge this does not guarantee that the records were really inserted. The transaction may still rollback after insertEnd()
was called - or the insert to one table may be part of a batch of inserts that also affects other tables.
If, on the other hand, I implement TransactionListener#comitEnd
I can't figure out which records where actually inserted. TransactionContext
doesn't have this information.
解决方案
You can do this by accessing the Configuration.data()
property, which has been created for this purpose. Consider these two listeners:
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");
}
}
This could then be used as follows:
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);
推荐阅读
- json - postgres 从 json 字段中选择作为每个键的列
- javascript - React js:为表格中的每个单元格设置状态
- google-cloud-platform - Google Compute Engine 是否支持发出 aiohttp 获取请求?
- python - 如何使用两个数组和引用将带有“interp1”的 Matlab 函数转换为带有“interp1d”的 Python
- json - 如何在 Json 中解码多/单值
- grails - 如何覆盖 grails 隐式日志变量
- java - mockMvc.perform 上的错误。空指针异常
- java - 在类 org.demo.mypackage1.C 中可以通过它们的短名称访问什么而不编写任何导入?
- php - 使用 php 变量设置 HTML 表格单元格标题
- python - 如何从单行字符串中查找子字符串