How to specify a jdbc.url in the persistence.xml relative to the application folder?

大城市里の小女人 提交于 2019-12-24 07:29:08

问题


Once I deploy my application with JPA the user chooses to install it somewhere. Then however the property set as:

<property name="javax.persistence.jdbc.url" value="jdbc:derby:db;create=true"/>

gets interpreted into the following exception: couldn't create database in \db. Throughout development it used to be the relative path to the project folder, and not the root as it's now. What should I do to make the path remain relative to the folder in which the application is installed? Or at the very worse, the userdir.


回答1:


You should write the install location somewhere and set the derby.system.home system property to this location before creating the connection. Quoting the Using Java DB in Desktop Applications article:

Connecting to the Java DB Database

...

All connection URLs have the following form:

jdbc:derby:<dbName>[propertyList]

The dbName portion of the URL identifies a specific database. A database can be in one of many locations: in the current working directory, on the classpath, in a JAR file, in a specific Java DB database home directory, or in an absolute location on your file system. The easiest way to manage your database location in an embedded environment is to set the derby.system.home system property. This property tells Java DB the default home location of all databases. By setting this property, the Address Book demo ensures that Java DB always finds the correct application database. The application database is named DefaultAddressBook, and it will exist within the directory indicated by the derby.system.home property. The connection URL for this database would look like this:

jdbc:derby:DefaultAddressBook

...

To connect to the DefaultAddressBook database, the demo must first set the derby.system.home system property. The demo uses the .addressbook subdirectory of the user's home directory. Use the System class to find out the user's home directory. Then use the class again to set the derby.system.home property:

private void setDBSystemDir() {
    // Decide on the db system directory: <userhome>/.addressbook/
    String userHomeDir = System.getProperty("user.home", ".");
    String systemDir = userHomeDir + "/.addressbook";

    // Set the db system directory.
    System.setProperty("derby.system.home", systemDir);
}


来源:https://stackoverflow.com/questions/3430723/how-to-specify-a-jdbc-url-in-the-persistence-xml-relative-to-the-application-fol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!