可用版本:Dev (3.21) | 最新 (3.20) | 3.19 | 3.18

上下文转换器

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

上一节讨论了通用的 数据类型转换 API,它由 org.jooq.Converter 类型表示。与 org.jooq.Binding 不同,Converter 无法以任何方式访问 org.jooq.Configuration,因此,将第三方逻辑依赖注入到转换器中变得困难。一个常见的用例是实现基于 Jackson 的 JSON 处理转换器,并在某处配置 Jackson ObjectMapper。使用 Converter,实现此目的的唯一方法包括:

  • 在某处创建一个 static 全局变量并访问它。
  • 在执行查询之前,使用 java.lang.ThreadLocal

这两种选择当然都是可行的,但感觉不太对。这就是为什么引入了一个新的 org.jooq.ContextConverter,它是 org.jooq.Converter 的一个子类型,暴露了额外的方法:

// A ContextConverter can be used wherever a Converter can be used
public interface ContextConverter<T, U> extends Converter<T, U> {

    // Additional, specialised from(T):U and to(U):T methods receive a ConverterContext type,
    // which gives access to your Configuration from within the ContextConverter
    U from(T databaseObject, ConverterContext ctx);
    T to(U userObject, ConverterContext ctx);

    // The usual Converter methods don't have to be implemented and won't be called by
    // jOOQ internals, if you're implementing ContextConverter. The default implementation
    // uses an unspecified, internal ConverterContext
    @Override
    default T to(U userObject) {
        return to(userObject, converterContext());
    }

    @Override
    default U from(T databaseObject) {
        return from(databaseObject, converterContext());
    }
}

如果您为 jOOQ 提供一个 org.jooq.ContextConverter,那么 jOOQ 将保证调用更专门的 from()to() 方法,这些方法接收一个 org.jooq.converterContext,该上下文提供对无处不在的 org.jooq.Configuration 的访问。为了为您的 ContextConverter 提供自定义配置,只需使用 Configuration::data

// Configuring your Configuration, e.g. with Spring:
Configuration configuration = new DefaultConfiguration();
configuration.data("my-configuration-key", myConfigurationValue);

// And then:
public class MyContextConverter implements ContextConverter<Integer, String> {
    @Override
    public String from(Integer databaseObject, ConverterContext ctx) {
        if (ctx.configuration().data("my-configuration-key") != null)
            return "configuration enabled";
        else
            return "configuration disabled";
    }
}

反馈

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

The jOOQ Logo