2012-06-30

Embedded, persistent key-store

One often needs an embedded, persistent, key-store database solution if he/she is developing a software which relies on configurations made upon deployment. I was that one yesterday, so I looked up on the Internet for a solution. The solution was, with no convincing reason, Berkeley DB Java Edition, Sleepy Cat to be specific.

So here is the code chunk that did the trick! For a developer of modern languages like Python, it seemed like a lot of work for simple tasks. However, if you wrap it with your own code it can be helpful in many ways.


public static void main(String[] args) throws DatabaseException,
UnsupportedEncodingException {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
EnvironmentConfig config = new EnvironmentConfig();
config.setAllowCreate(true);
config.setTransactional(true);
Environment environ = new Environment(new File("sleepydb"), config);
DatabaseConfig databaseConfig = new DatabaseConfig();
databaseConfig.setAllowCreate(true);
Database db = environ.openDatabase(null, "company",
databaseConfig);
db.put(null, new DatabaseEntry("name".getBytes("utf-8")),
new DatabaseEntry("Example company".getBytes("utf-8")));
key.setData("name".getBytes("utf-8"));
db.get(null, key, data, LockMode.DEFAULT);
System.out.println(new String(data.getData(), "utf-8"));
db.close();
environ.close();
}
view raw gistfile1.java hosted with ❤ by GitHub