简体   繁体   中英

Build Left Join Query with JOOQ using two Tables from two Different Databases

We are using JOOQ for all our queries execution.

Now we need to create left join query with JOOQ, what will left join two tables from two different databases

Example native SQL query (bellow), we need this query to be build using JOOQ framework and not use native sql. Until now i did't find any solution, maybe this functionality is not supported by JOOQ

SELECT * 
FROM `library`.`books` 
LEFT JOIN `library2`.`author2` ON `library`.`books`.`author_id` = `library2`.`author2`.`id`

Code generator configuration

If you want to work with two different databases / schemas, you'll need to configure the code generator accordingly. You can specify several input schemata as documented here :

<configuration>
  <generator>
    <database>
      <schemata>
        <schema>
          <inputSchema>library</inputSchema>
        </schema>
        <schema>
          <inputSchema>library2</inputSchema>
        </schema>
      </schemata>
    </database>
  </generator>
</configuration>

Alternatives:

  • You can just leave away the <inputSchema/> configuration and jOOQ's code generator would simply generate all the available schemata.
  • You could configure several independent code generations, one per schema. That would mean that your schemata don't have linking metadata (eg foreign keys) shared among each other.

Query

The jOOQ manual recommends referencing tables from a global generated Tables class . This works well for single-schema setups. When querying several schemata, it may be worth referencing tables from the generated schema instance instead. Here's how to write your query:

import static com.example.generated.library .Library .LIBRARY ;
import static com.example.generated.library2.Library2.LIBRARY2;
//                                  ^^^^^^^^ ^^^^^^^^ ^^^^^^^^
//                                     |        |        |
// Package per schema -----------------+        |        |
// Schema class       --------------------------+        |
// Schema instance    -----------------------------------+

And then:

DSL.using(configuration)
   .select()
   .from(LIBRARY.BOOKS)
   .leftJoin(LIBRARY2.AUTHOR2)
   .on(LIBRARY.BOOKS.AUTHOR_ID.eq(LIBRARY2.AUTHOR2.ID))
   .fetch();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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