可用版本:Dev (3.21) | 最新 (3.20) | 3.19 | 3.18 | 3.17 | 3.16 | 3.15 | 3.14 | 3.13 | 3.12 | 3.11

自定义数据

适用于 ✅ 开源版   ✅ 专业版   ✅ 企业版

在将应用程序与 jOOQ 集成的高级用例中,您可能希望将自定义数据放入您的 Configuration 中,然后您可以从以下位置访问它...

这是一个关于如何使用自定义数据 API 的示例。 假设您已经编写了一个 ExecuteListener,当给定标志设置为 true 时,它会阻止 INSERT 语句

public class NoInsertListener implements ExecuteListener {

    @Override
    public void start(ExecuteContext ctx) {

        // This listener is active only, when your custom flag is set to true
        if (Boolean.TRUE.equals(ctx.configuration().data("com.example.my-namespace.no-inserts"))) {

            // If active, fail this execution, if an INSERT statement is being executed
            if (ctx.query() instanceof Insert) {
                throw new DataAccessException("No INSERT statements allowed");
            }
        }
    }
}

请参阅手册中关于 ExecuteListeners 的章节,以了解更多关于如何实现 ExecuteListener 的信息。

现在,可以将上述侦听器添加到您的 Configuration 中,但您还需要将标志传递给 Configuration,以便侦听器可以工作

// Create your Configuration
Configuration configuration = new DefaultConfiguration().set(connection).set(dialect);

// Set a new execute listener provider onto the configuration:
configuration.set(new DefaultExecuteListenerProvider(new NoInsertListener()));

// Use any String literal to identify your custom data
configuration.data("com.example.my-namespace.no-inserts", true);

// Try to execute an INSERT statement
try {
    DSL.using(configuration)
       .insertInto(AUTHOR, AUTHOR.ID, AUTHOR.LAST_NAME)
       .values(1, "Orwell")
       .execute();

    // You shouldn't get here
    Assert.fail();
}

// Your NoInsertListener should be throwing this exception here:
catch (DataAccessException expected) {
    Assert.assertEquals("No INSERT statements allowed", expected.getMessage());
}

使用 data() 方法,您可以在 Configurations 中存储和检索自定义数据。

反馈

您对此页面有任何反馈吗? 我们很乐意听取您的意见!

The jOOQ Logo