如何修复:Jooq 代码不会从 sql 脚本为内存 db 中的 sqlite 生成 java 代码

Posted

技术标签:

【中文标题】如何修复:Jooq 代码不会从 sql 脚本为内存 db 中的 sqlite 生成 java 代码【英文标题】:How to fix: Jooq code does not generate java code for sqlite in memory db from sql script 【发布时间】:2020-02-16 08:34:08 【问题描述】:

我正在尝试生成与内存 SQLite 一起使用的 Jooq 代码。 问题是,每个新连接都会创建一个新的 SQLite 实例,这使得代码创建依赖于 sql 脚本。但是,当我尝试将代码生成与documentation 匹配时,不会生成代码。我相信它仍然会尝试访问为空的数据库。

我也不确定 jooq 是否可以与非持久性数据库一起使用。该数据库旨在仅在程序运行期间存在。当程序关闭时,数据库应该消失了。如果 jooq 在整个运行时都获取新连接,我无论如何都必须切换。

Jooq 世代:

public static void runJooqCodeGen() throws Exception 
    String url = "jdbc:sqlite:";
    String driver = "org.sqlite.JDBC";
    Configuration configuration = new Configuration().withJdbc(new Jdbc().withDriver(driver).withUrl(url))
            .withGenerator(new Generator()
                    .withDatabase(new Database()
                            .withProperties(new Property()
                                    .withKey("scripts")
                                    .withValue("src/main/resources/db/Schema.sql")))
                    .withGenerate(new Generate()
                            .withPojos(Boolean.TRUE)
                            .withDeprecationOnUnknownTypes(Boolean.FALSE))
                    .withTarget(new Target()
                            .withPackageName("me.leslie.generals.server.persistence.jooq")
                            .withDirectory("Generals-Server/src/main/java")));

    GenerationTool.generate(configuration);

src/main/resources/db/Schema.sql:

CREATE TABLE IF NOT EXISTS TROOP(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    current_health INTEGER NOT NULL,
    max_health INTEGER NOT NULL,
    pos_x DOUBLE NOT NULL,
    pos_y DOUBLE NOT NULL,
    normal_speed DOUBLE NOT NULL,
    street_speed DOUBLE NOT NULL,
    difficult_terrain_speed DOUBLE NOT NULL,
    close_combat_range DOUBLE NOT NULL,
    ranged_combat_range DOUBLE NOT NULL,
    normal_view_distance DOUBLE NOT NULL,
    disadvantaged_view_distance DOUBLE NOT NULL,
    advantaged_view_distance DOUBLE NOT NULL
);

CREATE TABLE IF NOT EXISTS ARMY(
    id INTEGER,
    hq INTEGER,
    troop INTEGER,
    FOREIGN KEY(hq) REFERENCES TROOP(id),
    FOREIGN KEY(troop) REFERENCES TROOP(id),
    UNIQUE(hq, troop),
    PRIMARY KEY (id, hq, troop)
);

生成没有以错误结束,但这是控制台输出。

19:02:57.342 [main] DEBUG org.jooq.codegen.GenerationTool - Input configuration      : <onError>FAIL</onError><jdbc><driver>org.sqlite.JDBC</driver><url>jdbc:sqlite:</url></jdbc><generator><name>org.jooq.codegen.DefaultGenerator</name><database><regexMatchesPartialQualification>true</regexMatchesPartialQualification><sqlMatchesPartialQualification>true</sqlMatchesPartialQualification><includes>.*</includes><excludes></excludes><includeExcludeColumns>false</includeExcludeColumns><includeTables>true</includeTables><includeEmbeddables>true</includeEmbeddables><includeRoutines>true</includeRoutines><includeTriggerRoutines>false</includeTriggerRoutines><includePackages>true</includePackages><includePackageRoutines>true</includePackageRoutines><includePackageUDTs>true</includePackageUDTs><includePackageConstants>true</includePackageConstants><includeUDTs>true</includeUDTs><includeSequences>true</includeSequences><includeIndexes>true</includeIndexes><includePrimaryKeys>true</includePrimaryKeys><includeUniqueKeys>true</includeUniqueKeys><includeForeignKeys>true</includeForeignKeys><includeCheckConstraints>true</includeCheckConstraints><includeInvisibleColumns>true</includeInvisibleColumns><recordVersionFields></recordVersionFields><recordTimestampFields></recordTimestampFields><syntheticIdentities></syntheticIdentities><syntheticPrimaryKeys></syntheticPrimaryKeys><overridePrimaryKeys></overridePrimaryKeys><dateAsTimestamp>false</dateAsTimestamp><ignoreProcedureReturnValues>false</ignoreProcedureReturnValues><unsignedTypes>true</unsignedTypes><integerDisplayWidths>true</integerDisplayWidths><inputCatalog></inputCatalog><outputCatalogToDefault>false</outputCatalogToDefault><inputSchema></inputSchema><outputSchemaToDefault>false</outputSchemaToDefault><schemaVersionProvider></schemaVersionProvider><catalogVersionProvider></catalogVersionProvider><orderProvider></orderProvider><forceIntegerTypesOnZeroScaleDecimals>true</forceIntegerTypesOnZeroScaleDecimals><logSlowQueriesAfterSeconds>5</logSlowQueriesAfterSeconds><logSlowResultsAfterSeconds>5</logSlowResultsAfterSeconds><properties><property><key>scripts</key><value>src/main/resources/db/Schema.sql</value></property></properties></database><generate><indexes>true</indexes><relations>true</relations><implicitJoinPathsToOne>true</implicitJoinPathsToOne><deprecated>true</deprecated><deprecationOnUnknownTypes>false</deprecationOnUnknownTypes><instanceFields>true</instanceFields><generatedAnnotation>true</generatedAnnotation><generatedAnnotationType>DETECT_FROM_JDK</generatedAnnotationType><routines>true</routines><sequences>true</sequences><udts>true</udts><queues>true</queues><links>true</links><keys>true</keys><tables>true</tables><embeddables>true</embeddables><records>true</records><recordsImplementingRecordN>true</recordsImplementingRecordN><pojos>true</pojos><pojosEqualsAndHashCode>false</pojosEqualsAndHashCode><pojosToString>true</pojosToString><immutablePojos>false</immutablePojos><serializablePojos>true</serializablePojos><interfaces>false</interfaces><immutableInterfaces>false</immutableInterfaces><serializableInterfaces>true</serializableInterfaces><daos>false</daos><jpaAnnotations>false</jpaAnnotations><validationAnnotations>false</validationAnnotations><springAnnotations>false</springAnnotations><globalObjectReferences>true</globalObjectReferences><globalCatalogReferences>true</globalCatalogReferences><globalSchemaReferences>true</globalSchemaReferences><globalTableReferences>true</globalTableReferences><globalSequenceReferences>true</globalSequenceReferences><globalUDTReferences>true</globalUDTReferences><globalRoutineReferences>true</globalRoutineReferences><globalQueueReferences>true</globalQueueReferences><globalLinkReferences>true</globalLinkReferences><globalKeyReferences>true</globalKeyReferences><javadoc>true</javadoc><comments>true</comments><commentsOnCatalogs>true</commentsOnCatalogs><commentsOnSchemas>true</commentsOnSchemas><commentsOnTables>true</commentsOnTables><commentsOnColumns>true</commentsOnColumns><commentsOnUDTs>true</commentsOnUDTs><commentsOnAttributes>true</commentsOnAttributes><commentsOnPackages>true</commentsOnPackages><commentsOnRoutines>true</commentsOnRoutines><commentsOnParameters>true</commentsOnParameters><commentsOnSequences>true</commentsOnSequences><commentsOnLinks>true</commentsOnLinks><commentsOnQueues>true</commentsOnQueues><commentsOnKeys>true</commentsOnKeys><fluentSetters>false</fluentSetters><javaBeansGettersAndSetters>false</javaBeansGettersAndSetters><varargSetters>true</varargSetters><fullyQualifiedTypes></fullyQualifiedTypes><emptyCatalogs>false</emptyCatalogs><emptySchemas>false</emptySchemas><javaTimeTypes>false</javaTimeTypes><primaryKeyTypes>false</primaryKeyTypes><newline>\n</newline></generate><target><packageName>me.leslie.generals.server.persistence.jooq</packageName><directory>Generals-Server/src/main/java</directory><encoding>UTF-8</encoding><clean>true</clean></target></generator>
19:02:57.424 [main] INFO org.jooq.codegen.GenerationTool - Database                 : Inferring database org.jooq.meta.sqlite.SQLiteDatabase from URL jdbc:sqlite:
19:02:57.426 [main] INFO org.jooq.codegen.GenerationTool - No <inputCatalog/> was provided. Generating ALL available catalogs instead.
19:02:57.426 [main] INFO org.jooq.codegen.GenerationTool - No <inputSchema/> was provided. Generating ALL available schemata instead.
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - License parameters       
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   Thank you for using jOOQ and jOOQ's code generator
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -                          
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - Database parameters      
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   dialect                : SQLITE
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   URL                    : jdbc:sqlite:
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   target dir             : Generals-Server/src/main/java
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   target package         : me.leslie.generals.server.persistence.jooq
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   includes               : [.*]
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   excludes               : []
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -   includeExcludeColumns  : false
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -                          
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - JavaGenerator parameters 
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   annotations (generated): true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   annotations (JPA: any) : false
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   annotations (JPA: version): 
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   annotations (validation): false
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments               : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on attributes : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on catalogs   : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on columns    : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on keys       : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on links      : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on packages   : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on parameters : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on queues     : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on routines   : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on schemas    : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on sequences  : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on tables     : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   comments on udts       : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   daos                   : false
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   deprecated code        : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -   global references (any): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (catalogs): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (keys): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (links): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (queues): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (routines): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (schemas): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (sequences): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (tables): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   global references (udts): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   indexes                : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   instance fields        : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   interfaces             : false
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   interfaces (immutable) : false
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   javadoc                : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   keys                   : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   links                  : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   pojos                  : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   pojos (immutable)      : false
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   queues                 : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   records                : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   routines               : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   sequences              : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   table-valued functions : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   tables                 : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   udts                   : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -   relations              : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - ----------------------------------------------------------
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -                          
19:02:57.525 [main] INFO org.jooq.codegen.AbstractGenerator - Generation remarks       
19:02:57.525 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -                          
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - ----------------------------------------------------------
19:02:57.526 [main] INFO org.jooq.codegen.JavaGenerator - Generating catalogs      : Total: 1
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - ARRAYs fetched           : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Enums fetched            : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Packages fetched         : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Routines fetched         : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Sequences fetched        : 0 (0 included, 0 excluded)
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.jooq.tools.reflect.Reflect (file:/home/leslie/.m2/repository/org/jooq/jooq/3.12.1/jooq-3.12.1.jar) to constructor java.lang.invoke.MethodHandles$Lookup(java.lang.Class)
WARNING: Please consider reporting this to the maintainers of org.jooq.tools.reflect.Reflect
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
19:02:57.725 [main] INFO org.jooq.Constants - 

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@  @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@        @@@@@@@@@@
@@@@@@@@@@@@@@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@  @@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@        @@  @  @  @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@  @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  Thank you for using jOOQ 3.12.1

19:02:57.732 [main] DEBUG org.jooq.tools.LoggerListener - Executing query          : select 1 one
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - Fetched result           : +----+
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener -                          : | one|
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener -                          : +----+
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener -                          : |   1|
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener -                          : +----+
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - Fetched row(s)           : 1
19:02:57.791 [main] DEBUG org.jooq.tools.LoggerListener - Executing query          : select sqlite_master.name from sqlite_master where sqlite_master.type in (?, ?) order by sqlite_master.name
19:02:57.792 [main] DEBUG org.jooq.tools.LoggerListener - -> with bind values      : select sqlite_master.name from sqlite_master where sqlite_master.type in ('table', 'view') order by sqlite_master.name
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener - Fetched result           : +----+
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener -                          : |name|
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener -                          : +----+
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener - Fetched row(s)           : 0
19:02:57.793 [main] INFO org.jooq.meta.AbstractDatabase - Tables fetched           : 0 (0 included, 0 excluded)
19:02:57.793 [main] INFO org.jooq.meta.AbstractDatabase - UDTs fetched             : 0 (0 included, 0 excluded)
19:02:57.793 [main] INFO org.jooq.codegen.JavaGenerator - Excluding empty catalog  : 
19:02:57.793 [main] INFO org.jooq.codegen.JavaGenerator - Removing excess files    

Process finished with exit code 0

【问题讨论】:

【参考方案1】:

如果您想使用DDLDatabase 所记录的in the link you've posted,您应该:

移除 JDBC 连接参数 将DDLDatabase 添加为数据库实现,以替换默认的SQLiteDatabase(源自您的JDBC 连接参数)。

换句话说,试试这个:

public static void runJooqCodeGen() throws Exception 
    // Removed this
    /* String url = "jdbc:sqlite:";
    String driver = "org.sqlite.JDBC"; */
    Configuration configuration = new Configuration()/*.withJdbc(new Jdbc()
            .withDriver(driver).withUrl(url))*/
        .withGenerator(new Generator()
            .withDatabase(new Database()
                // Added this
                .withName("org.jooq.meta.extensions.ddl.DDLDatabase")
                .withProperties(new Property()
                    .withKey("scripts")
                    .withValue("src/main/resources/db/Schema.sql")))
                .withGenerate(new Generate()
                    .withPojos(Boolean.TRUE)
                    .withDeprecationOnUnknownTypes(Boolean.FALSE))
                .withTarget(new Target()
                    .withPackageName("me.leslie.generals.server.persistence.jooq")
                    .withDirectory("Generals-Server/src/main/java")));

    GenerationTool.generate(configuration);

【讨论】:

非常感谢。这有帮助。此外,我必须将 sql 文件的路径更改为 "/db/Schema.sql",然后一切都按预期工作。 @Leslie:澄清一下:/dbSchema.sql 符号将在类路径中查找文件。 src/main/resources/db/Schema.sql 表示法将从执行目录中查找它,该目录可能在您认为的位置,也可能不在。您还可以使用**/*/ 通配符。

以上是关于如何修复:Jooq 代码不会从 sql 脚本为内存 db 中的 sqlite 生成 java 代码的主要内容,如果未能解决你的问题,请参考以下文章

如何从 SQL 查询配置 jOOQ 可嵌入类型

使用 JOOQ 从 MS SQL 数据库生成代码时遇到问题

无法修复 JOOQ 查询中的“未知表”异常

Information_schema 未从 jooq for SQL Server 生成

使用 Spring Boot 进行 JOOQ SQL 语法转换

如何使用 jOOQ 将 Oracle PL/SQL 常量作为参数传递?