简体   繁体   English

jooQ 3.13 插入批次并更改一列

[英]jooQ 3.13 insert batch with change one column

I have table Car in two DB.我在两个数据库中有表 Car。 Car in first table has column details as TEXT, in second has column details as JSONB.第一个表中的汽车的列详细信息为 TEXT,第二个表中的列详细信息为 JSONB。 But I have only one generated class with TEXT field.但是我只有一个生成的带有 TEXT 字段的 class 。 How can I do batch insert into table 2 using generated class Car and I need to change field from TEXT to JSONB.如何使用生成的 class Car批量插入表 2,我需要将字段从 TEXT 更改为 JSONB。 I insert into table with dsl.batchInsert(records).execute();我用dsl.batchInsert(records).execute();插入表

And its my field in jooq generated class它在jooq中的我的领域生成了class

public final TableField<Car, String> DETAILS = createField("details", org.jooq.impl.SQLDataType.TExT.nullable(false).defaultValue(org.jooq.impl.DSL.field("", org.jooq.impl.SQLDataType.TEXT)), this, "");

I need insert into second table smth like dsl.batchInsert(changeTextToJsonB(records)).execute();我需要像dsl.batchInsert(changeTextToJsonB(records)).execute();这样插入第二个表or smth else或其他

The obvious answer is to generate two sets of classes, one for each DB, but I'm assuming this doesn't work for you.显而易见的答案是生成两组类,每个数据库一组,但我假设这对你不起作用。

You could then implement a custom data type binding and attach that to your column using the code generator.然后,您可以实现自定义数据类型绑定并使用代码生成器将其附加到您的列。 Your binding could read some context variable, eg from a ThreadLocal for a quick and dirty solution, or from your Configuration.data() map to decide whether it wants to delegate to the VARCHAR binding or to the JSONB binding.您的绑定可以读取一些上下文变量,例如从ThreadLocal读取一个快速而肮脏的解决方案,或者从您的Configuration.data() map 来决定它是要委托给VARCHAR绑定还是委托给JSONB绑定。

public class TextOrJsonBinding implements Binding<String, String> {

    @Override
    public void set(BindingSetStatementContext<U> ctx) throws SQLException {
        var db = ctx.configuration().data("my-db");

        if ("db1".equals(db))
            SQLDataType.VARCHAR.getBinding().set(ctx);
        else if ("db2".equals(db))
            SQLDataType.JSONB.getBinding().set(ctx);
        else
            throw new DataAccessException("Unsupported DB: " + db);
    }

    // Repeat for all methods
}

With the above approach, you can now have two configurations for each DB (you probably already do, because you probably have different DataSource instances):使用上述方法,您现在可以为每个 DB 进行两种配置(您可能已经这样做了,因为您可能有不同的DataSource实例):

Configuration db1 = new DefaultConfiguration();
db1.data("my-db", "db1");

Configuration db2 = new DefaultConfiguration();
db2.data("my-db", "db2");

// Produces VARCHAR bindings
db1.dsl().batchInsert(records).execute();

// Produces JSONB bindings
db2.dsl().batchInsert(records).execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM