问题
This is a follow-on question to my earlier question about specifying multiple schemata in java using jooq to interact with H2.
My test H2 DB currently has 2 schemata, PUBLIC and INFORMATION_SCHEMA. PUBLIC is specified as the default schema by H2. When running a query that should extract information from eg INFORMATION_SCHEMA.TABLES the query fails with a "table unknown" SQL error. I am only able to execute such queries by executing a factory.use(INFORMATION_SCHEMA)
. There are no build errors etc and eclipse properly autocompletes eg TABLES.TABLE_NAME.
If I dont do this, jooq doesnt seem to prepend the appropriate schema even though I create the correct Factory object for the schema eg
InformationSchemaFactory info = new InformationSchemaFactory(conn);
I read about mapping but am a bit confused as to which schema I would use as the input/output.
回答1:
By default, the InformationSchemaFactory
assumes that the supplied connection is actually connected to the INFORMATION_SCHEMA
. That's why schema names are not rendered in SQL. Example:
// This query...
new InformationSchemaFactory(conn).selectFrom(INFORMATION_SCHEMA.TABLES).fetch();
// ... renders this SQL (with the asterisk expanded):
SELECT * FROM "TABLES";
The above behaviour should be documented in your generated InformationSchemaFactory
Javadoc. In order to prepend "TABLES"
with "INFORMATION_SCHEMA"
, you have several options.
Use a regular factory instead, which is not tied to any schema:
// This query... new Factory(H2, conn).selectFrom(INFORMATION_SCHEMA.TABLES).fetch(); // ... renders this SQL: SELECT * FROM "INFORMATION_SCHEMA"."TABLES";
Use another schema's factory, such as the generated
PublicFactory
:// This query... new PublicFactory(conn).selectFrom(INFORMATION_SCHEMA.TABLES).fetch(); // ... renders this SQL: SELECT * FROM "INFORMATION_SCHEMA"."TABLES";
Use Settings and an appropriate schema mapping to force the schema name to be rendered.
The first option is probably the easiest one.
This blog post here will give you some insight about how to log executed queries to your preferred logger output: http://blog.jooq.org/2011/10/20/debug-logging-sql-with-jooq/
来源:https://stackoverflow.com/questions/12070934/querying-the-appropriate-database-schema