通过命令行运行 Swing Maven jar 应用程序不会构建数据库,但从 NetBeans 运行相同的应用程序时会构建数据库,如何修复?

问题描述 投票:0回答:1

我使用 Apache derby 嵌入模式编写了一个 Maven Java swing 应用程序。

使用

flyway-database-derby
迁移数据库(创建数据库)。
使用
maven-shade-plugin
来“清理并构建”具有依赖项的 jar。
使用过 Apache NetBeans IDE 21

案例 A:从命令行运行应用程序

如果我使用命令行启动 jar 文件

java -jar warehouse-box-1.0-SNAPSHOT.jar
,它会输出以下消息:

C:\Users\Saleh\Documents\NetBeansProjects\warehouse-box\target>java -jar warehouse-box-1.0-SNAPSHOT.jar
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.resource.ResourceNameValidator - 1 SQL migrations were detected but not run because they did not follow the filename convention.
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.resource.ResourceNameValidator - Set 'validateMigrationNaming' to true to fail fast and see a list of the invalid file names.
[AWT-EventQueue-0] INFO org.flywaydb.core.FlywayExecutor - Database: jdbc:derby:C:\Users\Saleh\warehouse-db (Apache Derby 10.17)
[AWT-EventQueue-0] WARN org.flywaydb.core.internal.database.base.Database - Flyway upgrade recommended: Derby 10.17 is newer than this version of Flyway and support has not been tested. The latest supported version of Derby is 10.15.
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.database.base.Schema - Creating schema "ROOT" ...
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory - Creating Schema History table "ROOT"."flyway_schema_history" ...
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Current version of schema "ROOT": null
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Schema "ROOT" is up to date. No migration necessary.
  • GUI 启动。
  • 数据库目录已创建。
  • 但是,表并未创建。如果我通过命令行连接到 Apache derby;它不输出任何表格(我的表格)。
ij> connect 'jdbc:derby:C:\Users\Saleh\warehouse-db;user=root;password=1212';
ij> show tables; # My tables were not listed, they were not created.
ij> select * from items;
ERROR 42X05: Table/View 'ITEMS' does not exist.

案例 B:从 NetBeans 运行应用程序:(没有问题)

如果我从 Apache NetBeans 中运行应用程序,则没有问题;应用程序启动并创建数据库,一切顺利。 NetBeans 输出:

cd C:\Users\Saleh\Documents\NetBeansProjects\warehouse-box; "JAVA_HOME=C:\\Program Files\\Java\\jdk-20" cmd /c "\"C:\\Program Files\\NetBeans-21\\netbeans\\java\\maven\\bin\\mvn.cmd\" -Dexec.vmArgs= \"-Dexec.args=${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}\" -Dexec.appArgs= -Dexec.mainClass=warehousebox.root.MainRun \"-Dexec.executable=C:\\Program Files\\Java\\jdk-20\\bin\\java.exe\" \"-Dmaven.ext.class.path=C:\\Program Files\\NetBeans-21\\netbeans\\java\\maven-nblib\\netbeans-eventspy.jar\" --no-transfer-progress process-classes org.codehaus.mojo:exec-maven-plugin:3.1.0:exec"
Scanning for projects...

--------------------< com.salehrezq:warehouse-box >---------------------
Building warehouse-box 1.0-SNAPSHOT
  from pom.xml
--------------------------------[ jar ]---------------------------------

--- resources:3.3.1:resources (default-resources) @ warehouse-box ---
Copying 10 resources from src\main\resources to target\classes

--- compiler:3.11.0:compile (default-compile) @ warehouse-box ---
Nothing to compile - all classes are up to date

--- exec:3.1.0:exec (default-cli) @ warehouse-box ---
[AWT-EventQueue-0] INFO org.flywaydb.core.FlywayExecutor - Database: jdbc:derby:C:\Users\Saleh\warehouse-db (Apache Derby 10.17)
[AWT-EventQueue-0] WARN org.flywaydb.core.internal.database.base.Database - Flyway upgrade recommended: Derby 10.17 is newer than this version of Flyway and support has not been tested. The latest supported version of Derby is 10.15.
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbValidate - Successfully validated 2 migrations (execution time 00:02.396s)
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Current version of schema "ROOT": null
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Migrating schema "ROOT" to version "1 - warehouse db tables"
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Successfully applied 1 migration to schema "ROOT", now at version v1 (execution time 00:02.471s)
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time:  01:16 min
Finished at: 2024-09-04T16:15:19+03:00
------------------------------------------------------------------------

颠倒案例A和B的顺序

如果我首先使用 NetBeans 运行应用程序(情况 B),然后再运行;关闭它并使用命令行运行应用程序(案例 A),现在应用程序使用命令行启动并且可以顺利工作而不会出现问题,并且它与之前在案例 B 中创建的数据库进行交互。 所以,案例 A仅当我首先通过从 NetBeans 运行应用程序来创建数据库时,才能正常工作。 相反后命令行的输出:

C:\Users\Saleh\Documents\NetBeansProjects\warehouse-box\target>java -jar warehouse-box-1.0-SNAPSHOT.jar
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.resource.ResourceNameValidator - 1 SQL migrations were detected but not run because they did not follow the filename convention.
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.resource.ResourceNameValidator - Set 'validateMigrationNaming' to true to fail fast and see a list of the invalid file names.
[AWT-EventQueue-0] INFO org.flywaydb.core.FlywayExecutor - Database: jdbc:derby:C:\Users\Saleh\warehouse-db (Apache Derby 10.17)
[AWT-EventQueue-0] WARN org.flywaydb.core.internal.database.base.Database - Flyway upgrade recommended: Derby 10.17 is newer than this version of Flyway and support has not been tested. The latest supported version of Derby is 10.15.
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbValidate - Successfully validated 2 migrations (execution time 00:00.270s)
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Current version of schema "ROOT": 1
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Schema "ROOT" is up to date. No migration necessary.

pom.xml

(为了简洁起见,我省略了与主题无关的依赖项)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.salehrezq</groupId>
    <artifactId>warehouse-box</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>20</maven.compiler.source>
        <maven.compiler.target>20</maven.compiler.target>
        <exec.mainClass>warehousebox.root.MainRun</exec.mainClass>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.derby/derby -->
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.17.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.derby/derbytools -->
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derbytools</artifactId>
            <version>10.17.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.flywaydb/flyway-database-derby -->
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-database-derby</artifactId>
            <version>10.17.3</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.6.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>warehousebox.root.MainRun</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-source-plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.3.1</version>
            </plugin>
            <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-javadoc-plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>3.10.0</version>
            </plugin>
            <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-deploy-plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>3.1.3</version>
            </plugin>
        </plugins>
    </build>
</project>

数据库迁移和连接

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.flywaydb.core.Flyway;

public class Connect {

    // JDBC driver name and database URL
    private static final String JDBC_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
    private static final String DB_URL = "jdbc:derby:"
            + System.getProperty("user.home")
            + File.separator
            + "warehouse-db;create=true;collation=TERRITORY_BASED:PRIMARY";

    //  Database credentials
    private static final String USER = "root";
    private static final String PASS = "1212";

    // For atomic statements
    private static Connection conn;

    public static void buildDatabaseIfNotExist() {
        Properties p = new Properties();
        p.setProperty("validateMigrationNaming", "true");
        Flyway flyway = Flyway.configure().configuration(p).dataSource(DB_URL, USER, PASS).load();
        flyway.migrate();
    }

    public static Connection getConnection() {
        try {
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
        }
        return conn;
    }
}

迁徙路线的迁移文件

地点及名称:

NetBeansProjects\warehouse-box\src\main\resources\db\migration\V1__warehouse_db_tables.sql

NetBeans 结构:

.
└── Project/
    └── Other Sources/
        └── src/main/resources/
            └── db.migration/
                └── V1__warehouse_db_tables.sql

如果有人有兴趣重现整个体验;这是 github 上的应用程序:https://github.com/salehrezq/warehouse-box

java maven database-migration derby
1个回答
0
投票

终于找到问题了。问题在于您创建遮光罐的方式。

您需要在

org.apache.maven.plugins.shade.resource.ServicesResourceTransformer
中添加
maven-shade-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.6.0</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>warehousebox.root.MainRun</mainClass>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>

为什么需要添加

ServicesResourceTransformer

提供某些接口实现的 JAR 文件通常随 META-INF/services/ 目录,将接口映射到它们的 用于服务定位器查找的实现类。搬迁 这些实现类的类名,并合并多个 将同一接口实现到一个服务条目中。

我本地的输出(成功):

➜  ~ git:(master) ✗ java -jar warehouse-box-1.0-SNAPSHOT.jar
2024-09-07 15:29:01.002 java[15668:560994] WARNING: Secure coding is not enabled for restorable state! Enable secure coding by implementing NSApplicationDelegate.applicationSupportsSecureRestorableState: and returning YES.
[AWT-EventQueue-0] INFO org.flywaydb.core.FlywayExecutor - Database: jdbc:derby:/Users/anish/warehouse-db-1 (Apache Derby 10.17)
[AWT-EventQueue-0] WARN org.flywaydb.core.internal.database.base.Database - Flyway upgrade recommended: Derby 10.17 is newer than this version of Flyway and support has not been tested. The latest supported version of Derby is 10.15.
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.database.base.Schema - Creating schema "ROOT" ...
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory - Creating Schema History table "ROOT"."flyway_schema_history" ...
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Current version of schema "ROOT": null
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Migrating schema "ROOT" to version "1 - warehouse db tables"
[AWT-EventQueue-0] INFO org.flywaydb.core.internal.command.DbMigrate - Successfully applied 1 migration to schema "ROOT", now at version v1 (execution time 00:00.152s)
© www.soinside.com 2019 - 2024. All rights reserved.