java—是否可以检索rdf4j事务的更新语句?

xu3bshqb  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(348)

我正在尝试使用rdf4j在sparql更新查询上支持“干运行”功能。我想通知用户将插入/删除的语句,最好是从当前事务中获取语句。我的想法是:

conn.begin();
Update query = conn.prepareUpdate(queryString);
query.execute();
// Print statements in the transaction
System.out.println("Dry run completed.");
conn.rollback();
System.out.println("Dry run rolled back.");

有没有办法用rdf4j做到这一点?

tcbh2hod

tcbh2hod1#

(抄袭自https://github.com/eclipse/rdf4j/discussions/3163 )
你可以用一个 SailConnectionListener . 但是访问这个的方法有点笨拙。下面是一个例子:

Repository rep = new SailRepository(new MemoryStore());
try (SailRepositoryConnection conn = (SailRepositoryConnection) rep.getConnection()) {
    NotifyingSailConnection sailConn = (NotifyingSailConnection) conn.getSailConnection();
    sailConn.addConnectionListener(new SailConnectionListener() {

        @Override
        public void statementRemoved(Statement removed) {
            System.out.println("removed: " + removed);
        }

        @Override
        public void statementAdded(Statement added) {
            System.out.println("added: " + added);
        }
    });

    conn.begin();
    conn.add(FOAF.PERSON, RDF.TYPE, RDFS.CLASS);
    String update = "DELETE { ?p a rdfs:Class } INSERT { ?p rdfs:label \"Person\" } WHERE { ?p a rdfs:Class }";
    conn.prepareUpdate(update).execute();
    System.out.println("executed");
    conn.rollback();
    System.out.println("transaction aborted");
}

正如你所看到的,我们需要 RepositoryConnection 到特定类型以检索基础 SailConnection ,然后我们需要更进一步地 SailConnectionNotifyingSailConnection 能够注册 SailConnectionListener 在上面。此侦听器将接收单个语句的预提交添加和删除事件。运行上述代码将产生以下控制台输出:

added: (http://xmlns.com/foaf/0.1/Person, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2000/01/rdf-schema#Class)
removed: (http://xmlns.com/foaf/0.1/Person, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2000/01/rdf-schema#Class) [null]
added: (http://xmlns.com/foaf/0.1/Person, http://www.w3.org/2000/01/rdf-schema#label, "Person")
executed
transaction aborted

相关问题