gpt4 book ai didi

java - H2:无法从 jar 内的 sql 文件初始化数据库模式

转载 作者:行者123 更新时间:2023-12-01 04:49:23 27 4
gpt4 key购买 nike

我尝试在我的项目中使用 H2 数据库 (v1.3.170) 进行 JUnit 测试,但遇到了奇怪的行为。我有一个 jar,其中包含用于数据库模式初始化的所有 sql:

db_data.jar
|--schema
|--aliases.sql
|--tables.sql
|-- ...

我的类路径中有这个 jar 。但是当我执行下面的代码时 - 它抛出一个异常[见下文]:

CallableStatement initCall = conn.prepareCall("RUNSCRIPT FROM 'classpath:schema/aliases.sql'");
initCall.execute();

抛出的异常:

Caused by: org.h2.jdbc.JdbcSQLException: IO Exception: "java.io.FileNotFoundException: resource /schema/aliases.sql"; "classpath:schema/aliases.sql"; SQL statement:
RUNSCRIPT FROM 'classpath:schema/aliases.sql' [90031-170]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:158)
at org.h2.message.DbException.convertIOException(DbException.java:315)
at org.h2.command.dml.ScriptBase.openInput(ScriptBase.java:162)
at org.h2.command.dml.RunScriptCommand.update(RunScriptCommand.java:43)
at org.h2.command.CommandContainer.update(CommandContainer.java:75)
at org.h2.command.Command.executeUpdate(Command.java:230)
at org.h2.server.TcpServerThread.process(TcpServerThread.java:333)
at org.h2.server.TcpServerThread.run(TcpServerThread.java:149)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: resource /schema/aliases.sql
at org.h2.store.fs.FilePathDisk.newInputStream(FilePathDisk.java:285)
at org.h2.store.fs.FileUtils.newInputStream(FileUtils.java:209)
at org.h2.command.dml.ScriptBase.openInput(ScriptBase.java:160)
... 6 more

我看到在 org.h2.store.fs.FilePathDisk#newInputStream() 中,您显式地将 / 添加到 SQL 文件的路径:

public InputStream newInputStream() throws IOException {
//...
if (!fileName.startsWith("/")) {
fileName = "/" + fileName;
}
//...
return in;
}

您能解释一下上面的目的吗?以及如何处理异常?

提前致谢!

最佳答案

使用服务器模式时,资源(jar文件)需要在服务器端。

关于java - H2:无法从 jar 内的 sql 文件初始化数据库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15242382/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com