如何在Apache Jena中保存记录?

时间:2017-02-02 17:33:28

标签: java kotlin jena apache-jena

我想在持久的Apache Jena数据库中创建一个昵称为jd且电子邮件为john.doe@provider.com的人。

我写了以下代码:

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))
}

当我运行它时,我没有错误。

但是当我尝试从文件中读取数据时(请参阅下面的代码),查询找不到任何内容。

    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()
    }

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

您应该在end收到警告,因为您尚未提交交易。

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