2013-03-06 81 views
1

我想在我的項目中使用H2數據庫( v1.3.170)進行JUnit測試,並且遇到奇怪的行爲。 我有一個包含了DB模式初始化所有SQL一個罐子:H2:無法從罐子裏面的SQL文件初始化數據庫模式

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

我有這個罐子在我的類路徑中。但是,當我執行下面的代碼 - 它拋出一個異常[見下文]:

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

thown例外:

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; 
} 

你能解釋一下上面的目的嗎?以及如何處理異常?

在此先感謝!

+1

嘗試''classpath:/ schema/aliases.sql''(斜線在前面)。如果它不起作用,你的數據庫URL是什麼? (當使用服務器模式時,jar文件需要在服務器端。) – 2013-03-06 10:27:06

+0

你是對的托馬斯。問題在於aliases.sql在客戶端類路徑中,而不在TCP服務器類路徑中。 謝謝! – 2013-03-20 07:43:00

+0

謝謝!我現在已經添加了解決方案作爲答案。 – 2013-03-20 15:04:19

回答

1

資源(jar文件)需要使用服務器模式時,必須在服務器端。

-1

嘗試改變文件參考:

classpath*:schema/aliases.sql 
+1

這不起作用: 引起:org.h2.jdbc.JdbcSQLException:IO異常:「java.net.MalformedURLException:no protocol:classpath *:schema/aliases.sql」; 「類路徑*:模式/ aliases.sql」; SQL語句: RUNSCRIPT FROM'classpath *:schema/aliases.sql'[90031-170] – 2013-03-06 10:08:30