【问题标题】:JOOQ How to convert JSON based on other column value?JOOQ 如何根据其他列值转换 JSON?
【发布时间】:2019-02-19 17:58:51
【问题描述】:

假设我有一个表customer(int id, type varchar, preferences jsonb)type 可以是REGULARPREMIUM 等。根据列类型值,偏好 JSON 结构会有所不同。

从数据库加载客户记录时,如果 type=REGULAR 我想将其转换为 RegularCustomerPreferences 对象类型,如果 type=PREMIUM 我想将其转换转换为PremiumCustomerPreferences 对象类型。

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

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

【问题讨论】:

    标签: java jooq jsonb


    【解决方案1】:

    您显然不能以类型安全的方式执行此操作,因为您的 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

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 2021-03-25
      • 2020-02-06
      • 2021-06-07
      • 2020-10-21
      • 1970-01-01
      • 2021-04-20
      • 2021-06-19
      • 2020-01-04
      相关资源
      最近更新 更多