一般在使用sqlite的时候都是配置url为绝对路径,但是今天在测试代码的时候想到如果将 项目不到tomcat上之后,db文件总不能一直配置成绝对路径,肯定是项目中的某个位置, 因此对jdbc配置文件进行了修改:
jdbc.url=jdbc:sqlite:blog.db
db文件放在WEB-INF/classes下,运行后发现貌似没有问题,然而事实并不是这样QAQ
因为测试中初始化代码会自动根据bean创建表格,我想是不是生成了一个新的db文件呢, 然后我把初始化关掉之后,果然报错了。。。。。。ORZ,然后我在tomcat的bin目录中 找到了崭新的db文件。
百般尝试之后依旧如此,于是去看源码,然后在org.sqlite.core.CoreConnection中发现了这么一段:
private static final String RESOURCE_NAME_PREFIX = ":resource:";
private void open(int openModeFlags, int busyTimeout) throws SQLException {
// check the path to the file exists
if (!":memory:".equals(fileName) && !fileName.startsWith("file:") && !fileName.contains("mode=memory")) {
if (fileName.startsWith(RESOURCE_NAME_PREFIX)) {
String resourceName = fileName.substring(RESOURCE_NAME_PREFIX.length());
// search the class path
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
URL resourceAddr = contextCL.getResource(resourceName);
if (resourceAddr == null) {
try {
resourceAddr = new URL(resourceName);
}
catch (MalformedURLException e) {
throw new SQLException(String.format("resource %s not found: %s", resourceName, e));
}
}
try {
fileName = extractResource(resourceAddr).getAbsolutePath();
}
catch (IOException e) {
throw new SQLException(String.format("failed to load %s: %s", resourceName, e));
}
}
else {
File file = new File(fileName).getAbsoluteFile();
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
for (File up = parent; up != null && !up.exists();) {
parent = up;
up = up.getParentFile();
}
throw new SQLException("path to '" + fileName + "': '" + parent + "' does not exist");
}
// check write access if file does not exist
try {
if (!file.exists() && file.createNewFile())
file.delete();
}
catch (Exception e) {
throw new SQLException("opening db: '" + fileName + "': " + e.getMessage());
}
fileName = file.getAbsolutePath();
}
}
// load the native DB
try {
NativeDB.load();
db = new NativeDB();
}
catch (Exception e) {
SQLException err = new SQLException("Error opening connection");
err.initCause(e);
throw err;
}
db.open((SQLiteConnection)this, fileName, openModeFlags);
setBusyTimeout(busyTimeout);
}
这段代码的大概意思就是在非内存模式且url中开头不是以file:开头的情况下,先判断了url是否是以 :resource:开头,如果是,就以类加载路径进行寻找(获取类加载路径的绝对路径后加载数据库文件), 否则就直接以url路径为绝对路径加载数据库文件
于是对jdbc配置文件进行修改:
jdbc.url=jdbc:sqlite::resource:blog.db
搞定!!!