Available in versions: Dev (3.18)

This documentation is for the unreleased development version of jOOQ. Click on the above version links to get this documentation for a supported version of jOOQ.

Context Converter

Applies to ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

The previous section discussed the generic data type conversion API represented by the org.jooq.Converter type. Unlike org.jooq.Binding, a Converter does not get access to a org.jooq.Configuration in any way, and as such, makes dependency injection of third party logic into converters difficult. A common use-case is to implement a Jackson based converter for JSON processing, and to configure that Jackson ObjectMapper somewhere. With Converter, the only ways to do this include:

  • Creating a static global variable somewhere and accessing that.
  • Resorting to java.lang.ThreadLocal usage, before executing a query.

Both of these options are certainly viable, but don't feel right. This is why a new org.jooq.ContextConverter has been introduced, a subtype of the org.jooq.Converter, exposing additional methods:

// 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());
    }
}

If you provide jOOQ with an org.jooq.ContextConverter, then jOOQ will guarantee that the more specialised from() and to() methods are called, which are receiving a org.jooq.converterContext, which provides access to the ubiquitous org.jooq.Configuration. In order to provide your ContextConverter with custom configuration, just use 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";
    }
}

Feedback

Do you have any feedback about this page? We'd love to hear it!

The jOOQ Logo