Jooq dynamically change db's schema in generated query

前端 未结 1 858
终归单人心
终归单人心 2021-01-11 19:00

I have 2 similar schemas in simple database - \"develop\" and \"stage\". I have generated Java classes with Jooq for one of that schemas (\"develop\" for example). When jooq

相关标签:
1条回答
  • 2021-01-11 19:31

    You have several options, which can even be combined:

    Use the code generator's schema mapping feature

    If you want to avoid hard-wiring the "develop" schema name into your generated classes, you can rewrite that to some other schema name like this:

    <configuration>
      <generator>
        <database>
          <schemata>
            <schema>
              <inputSchema>develop</inputSchema>
              <outputSchema>stage</outputSchema>
            </schema>
          ...
    

    Of course, this just postpones the problem, because the schema name is still in the generated code. You can remove the name entirely from generated code by using the following option:

    <configuration>
      <generator>
        <database>
          <schemata>
            <schema>
              <inputSchema>develop</inputSchema>
              <outputSchemaToDefault>true</outputSchemaToDefault>
            </schema>
          ...
    

    This will now remove any schema references from generated code, so the generated classes can run on all your schemas (be sure to use the correct connection and search_path, of course!)

    I think this is the best option for you

    More details here: https://www.jooq.org/doc/latest/manual/code-generation/codegen-advanced/codegen-config-catalog-and-schema-mapping/

    Use the runtime schema mapping feature

    You can leave generated code as it is and rewrite all object references at runtime using Settings (which you supply to your jOOQ runtime Configuration). Again, you have the same two options:

    Mapping the schema name:

    new Settings().withRenderMapping(new RenderMapping()
      .withSchemata(new MappedSchema()
        .withInput("develop")
        .withOutput("stage")
      )
    );
    

    Removing all schema names:

    new Settings().withRenderSchema(false);
    

    More details here: https://www.jooq.org/doc/latest/manual/sql-building/dsl-context/custom-settings/settings-render-mapping/

    0 讨论(0)
提交回复
热议问题