Alibaba is a great library to work with RDF Store as a Java developer. It generates Java interfaces from RDF triples that are very easy to work with.
Here is a simple tutorial on how to start working with complex RDF data in Java.
Warning: Alibaba works with the latest version of OpenRDF Sesame. It is currently not supported by RDF4J project.
Start by installing Alibaba and generate Java objects.
You may create your own Java/Maven project for this purpose.
Time to connect to our RDF repository:
Repository repository = new HTTPRepository(REPOSITORY_SERVER_URL, REPOSITORY_NAME); repository.initialize(); ObjectRepository objectRepository = new ObjectRepositoryFactory() .createRepository(repository); objectRepository.initialize(); ObjectConnection objectConnection = objectRepository.getConnection();
Disconnect from repository:
objectConnection.close(); objectRepository.shutDown(); repository.shutDown();
Retreive data from RDF as Java objects:
public void doStuff() throws RepositoryException { Result<Person> persons = objectConnection.getObjects(Person.class); while (persons.hasNext()) { Person person = persons.next(); String name = person.getName(); } }
The beauty of working with objects instead of statements is the ability to with logical entities directly in the code, which is true to the Java spirit. The logic in your program becomes clear as day.
Create and insert new objects into RDF repository using Java classes.
This step was a little bit tricky to figure out. The reason was the way Alibaba saves triples into the store.
To do it right I had to “initialize” the object in the RDF Store first. You can do it by “getting” the object from the store first. If you ask the database for the object that doesn’t exist it will create an empty placeholder for your object and return a default ID:
Object o = objectConnection.getObject(id);
Next step is to tell Alibaba to make the object of a special class:
Girl girl = objectConnection.addDesignation(o, Girl.class);
You need to do it for each class type so I’ve created a template function:
public <T extends Person> T initObject(String uri, Class<T> classType) { ValueFactory vf = objectConnection.getValueFactory(); URI id = vf.createURI(uri); Object o = objectConnection.getObject(id); T unit = objectConnection.addDesignation(o, classType); return unit; }
Now you may fill your new object with some data and save it:
private void createNewPerson() throws RepositoryException { repository.begin(); Girl girl = repository.initObject(NAME, Girl.class); girl.setName("Elli"); repository.commit(); }
Make some one time changes to the data in your RDF Store by making casual updates directly with SPARQL:
public void changeMyId() { RepositoryConnection connection = repository.getConnection(); connection.begin(); connection.prepareUpdate(QueryLanguage.SPARQL, "INSERT ... WHERE...").execute(); connection.commit(); }