JOOQ:查询相似表

JOOQ: Querying similar tables

我有 2 个 table 几乎相同的情况。一个table用于查看和编辑数据,然后发布数据。发布数据后,它会进入另一个 table。本质上是 WIDGET 和 PUBLISHED_WIDGET 我已经为 1 table 实现了各种自定义搜索、排序、过滤和分页查询,现在我必须为另一个实现它。我正在尝试找到一种方法来抽象它并使用 TableLike.

示例:

create table widget (
   id int not null auto_increment,
   name varchar(64) not null,
   lang varchar(2),
   updated_by varchar(64),
   updated_on timestamp
//...
);

create table published_widget (
   id int not null auto_increment,
   name varchar(64) not null,
   lang varchar(2),
   updated_by varchar(64),
   updated_on timestamp
//...
);

我希望能够做这样的事情:

public class WidgetDao {
  private final TableLike<CommonWidget> table;
public Widget find(String rsql) {
  dslContext.selectFrom(table)
    .where(table.ID.eq("...").and(table.NAME.eq("...")
//      ...
}

这可能吗?

Table映射

您可以为此使用 runtime table mapping feature。选择您的 table 之一作为您的“基础 table”(例如 WIDGET),然后使用此 Settings:

的派生配置
Settings settings = new Settings()
    .withRenderMapping(new RenderMapping()
    .withSchemata(
        new MappedSchema().withInput("MY_SCHEMA")
                          .withTables(
         new MappedTable().withInput("WIDGET")
                          .withOutput("PUBLISHED_WIDGET"))));

然后:

public Widget find(String rsql) {
  // Alternatively, store this derived Configuration in your DAO for caching purposes
  dslContext.configuration()
            .derive(settings)
            .dsl()
            .selectFrom(WIDGET)
            .where(WIDGET.ID.eq("...").and(WIDGET.NAME.eq("..."))
            .fetch();
  // ...
}

这样的 Settings 将全局重命名(不是别名)table,Configuration

Table.rename()

生成的 table 对其进行了 rename() 操作,这使您可以在特定的基础上而不是全局地执行您想要的操作。根据您的用例,这可能更 suitable。同样,这与别名(影响生成的 SQL)不同。

同样,您将选择您的 similar/identical table 之一作为您的基础 table,并根据您的目的重命名它:

public Widget find(String rsql) {
  Widget table = WIDGET.rename(PUBLISHED_WIDGET.getQualifiedName());

  dslContext.selectFrom(table)
            .where(table.ID.eq("...").and(table.NAME.eq("..."))
            .fetch();
  // ...
}

此方法目前 (jOOQ 3.14) 仅存在于生成的 table 上,不存在于 org.jooq.Table 上,参见:https://github.com/jOOQ/jOOQ/issues/5242