A simple solution would be to use an embedded database stored locally on the disk (for example near the jar file). You can use h2, or even sqlite for this.
When loaded the program will check for the existence of the database, if it's not here, just play a setup SQL script that will create the database structure and initial data, otherwise you're good to go, just do the stuff that your application was created to do.
Here is a really simple example with h2 database:
Say you are packaging a SQL file named init.sql
in the /resources/
folder of your JAR, that will create a table, something like:
create table foobar(bazz VARCHAR);
insert into foobar values('foo');
insert into foobar values('bar');
// and so on
Then somewhere in your code, where you need to access the data you will try to load the DB or create it if it does not exists yet.
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();
}
After execution, you should have a file named foo.db
next to your application where lies the created tables etc.
This is a really simple example, of course you can use any wrapper around JDBC to avoid use of ResultSet etc, like spring jdbcTemplate, even to load the connection instance etc.