Search code examples
javakotlinjenaapache-jena

How do I save a record in Apache Jena?


I want to create a person with nick name jd and e-mail john.doe@provider.com in a persistent Apache Jena database.

I wrote following code:

var dataSet:Dataset? = null
val Dir = "data/MyDataSet"
dataSet = TDBFactory.createDataset(Dir)

dataSet.begin(ReadWrite.WRITE)
val model = dataSet.defaultModel
createPerson("john.doe@provider.com", model, "jd")
dataSet.end()
dataSet.close()

private fun createPerson(email: String, model: Model, nick: String) {
    val uuid = UUID.randomUUID()
    val uri = "http://mycompany.com/data/p-${uuid}"
    val person = model.createResource(uri)
    person.addProperty(VCARD.EMAIL, email)
    person.addProperty(VCARD.N,
            model.createResource()
                    .addProperty(VCARD.NICKNAME, nick))
}

When I run it, I get no errors.

But when I try to read the data from the file (see code below), the query doesn't find anything.

    ds.begin(ReadWrite.READ)
    val query = QueryFactory.create("""SELECT ?x
            WHERE { ?x  <http://www.w3.org/2001/vcard-rdf/3.0#EMAIL>  "john.doe@provider.com" }""")
    val qexec: QueryExecution
    try {
        qexec = QueryExecutionFactory.create(query, ds.defaultModel)
        val rs = qexec.execSelect()
        while (rs.hasNext()) {
            val solution = rs.nextSolution()
            System.out.println("")
        }
    }
    catch (throwable:Throwable) {
        logger.error("", throwable)
    }
    finally {
        ds.end()
    }

What's wrong with my code?


Solution

  • You should get a warning at end because you have not committed the transaction.

    dataSet.begin(ReadWrite.WRITE)
    val model = dataSet.defaultModel
    createPerson("john.doe@provider.com", model, "jd")
    dataSet.commit()
    dataSet.end()