Jena TDB2 can be used as an RDF datastore. Note that TDB (version 1 of Jena TDB) and TDB2 are not compatible with each other. TDB2 is per definition transactional (while TDB is not). In this post I give a simple example that
- create a new Jena TDB2 dataset,
- create a write transaction and write data to the datastore,
- create a read transaction and read the data from the datastore, and
- release resources associated with the dataset on writing and reading is done.
Create TDB2 Dataset
To create a Jena TDB2 dataset, we use the TDB2Factory
. Note that the class name is TDB2Factory and not TDBFactory. We need to specify a directory where our dataset will be created. Multiple datasets cannot be written to the same directory.
Path path = Paths.get(".").toAbsolutePath().normalize(); String dbDir = path.toFile().getAbsolutePath() + "/db/"; Location location = Location.create(dbDir); Dataset dataset = TDB2Factory.connectDataset(location);
Create WRITE Transaction and Write
dataset.begin(ReadWrite.WRITE); UpdateRequest updateRequest = UpdateFactory.create( "INSERT DATA { " + " \"Grace Hopper\" .}"); UpdateProcessor updateProcessor = UpdateExecutionFactory.create(updateRequest, dataset); updateProcessor.execute(); dataset.commit();
Create READ Transaction and Read
dataset.begin(ReadWrite.READ); QueryExecution qe = QueryExecutionFactory .create("SELECT ?s ?p ?o WHERE {?s ?p ?o .}", dataset); for (ResultSet results = qe.execSelect(); results.hasNext();) { QuerySolution qs = results.next(); String strValue = qs.get("?o").toString(); logger.trace("value = " + strValue); }
Release Dataset Resources and Run Application
The dataset resources can be release calling close() on the dataset.
dataset.close();
Running the application will cause a /db
directory to be created in the directory from where you run your application, which consists of the various files that represent your dataset.
Conclusion
In this post I have given a simple example creating a TDB2 dataset and writing to and reading from it. This code can be found on github.