簡単な解決策は、ディスク上にローカルに保存された組み込みデータベースを使用することです (たとえば、jar ファイルの近く)。これにはh2、またはsqliteを使用できます。
ロードされると、プログラムはデータベースの存在をチェックします。データベースが存在しない場合は、データベース構造と初期データを作成するセットアップ SQL スクリプトを実行します。そうでない場合は、アプリケーションがあったことを実行しますするために作成されました。
これは、h2 データベースを使用した非常に単純な例です。
init.sql
たとえば、JARのフォルダーに名前が付けられた SQL ファイルをパッケージ化するとし/resources/
ます。これにより、次のようなテーブルが作成されます。
create table foobar(bazz VARCHAR);
insert into foobar values('foo');
insert into foobar values('bar');
// and so on
次に、コードのどこかで、データにアクセスする必要がある場所で、DB をロードしようとするか、まだ存在しない場合は作成します。
Connection loadDatabase() throws Exception {
Class.forName("org.h2.Driver");
Connection con = null;
try {
// throws an exception if the database does not exists
con = DriverManager.getConnection("jdbc:h2:./foo.db;ifexists=true");
} catch (SQLException e) {
// if the database does not exists it will be created
conn = DriverManager.getConnection("jdbc:h2:./foo.db");
// init the db
initDatabase(con);
}
return con;
}
void initDatabase(Connection con) throws Exception {
// load the init.sql script from JAR
InputStreamReader isr = new InputStreamReader(
getClass().getResourceAsStream("/resources/init.sql"));
// run it on the database to create the whole structure, tables and so on
RunScript.execute(con, isr);
isr.close();
}
void doSomeStuffWithDb() throws Exception {
Connection con = loadDatabase();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from foobar");
// will print foo, then bar
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
stmt.close();
conn.close();
}
実行後foo.db
、作成されたテーブルなどがあるアプリケーションの横に名前の付いたファイルが必要です。
これは非常に単純な例です。もちろん、JDBC の任意のラッパーを使用して、Spring jdbcTemplate などの ResultSet などの使用を回避し、接続インスタンスなどをロードすることもできます。