JOOQ如何根据其他列值转换JSON?

JOOQ How to convert JSON based on other column value?

假设我有一个 table 客户(int id,type varchar,preferences jsonb)type 可以是 REGULARPREMIUM 等。根据列类型值,首选项 JSON 结构会有所不同。

从数据库加载客户记录时 if type=REGULAR 我想将其转换为 RegularCustomerPreferences 对象类型,并且 if type=PREMIUM 我想把它转换成PremiumCustomerPreferences对象类型。

我已经阅读了几个关于使用 JOOQ 的教程 JSON converters/Bindings..但是它们是一对一的映射而不是基于条件的(取决于另一个列值)。

实现这个的理想方法是什么?

您显然不能以类型安全的方式执行此操作,因为您的 preferences 列的类型将是 Field<RegularCustomerPreferences | PremiumCustomerPreferences>(联合类型),并且 Java 当前不支持联合类型。因此,您可以将一个常见的 CustomerPreferences 超类型绑定到该列,并在使用它的任何地方向下转换该值。

绑定超类型应该比较容易。您将实现一个 Binding<Object, CustomerPreferences>,它可以处理 RegularCustomerPreferencesPremiumCustomerPreferences 值。具体来说,您的转换器看起来像这样:

public Converter<Object, CustomerPreferences> converter() {
    return new Converter<Object, CustomerPreferences>() {
        @Override
        public CustomerPreferences from(Object t) {
            if (some check here to see if this is a regular customer)
                return new RegularCustomerPreferences(t);
            else
                return new PremiumCustomerPreferences(t);
        }

        @Override
        public Object to(CustomerPreferences u) {
            return MyJSONTools.toJSON(u);
        }

        @Override
        public Class<Object> fromType() {
            return Object.class;
        }

        @Override
        public Class<CustomerPreferences> toType() {
            return CustomerPreferences.class;
        }
    };
}

这里的假设是您的 JSON 内容允许决定 JSON 文档应该有什么类型,与 type 列冗余,因为目前,从版本3.11 和 3.12,jOOQ 不支持多列数据类型绑定,这些绑定读取多个值以作为其数据类型转换决策的基础。这是与以下相关的待定功能:https://github.com/jOOQ/jOOQ/issues/6124