Parameterized SPARQL query with JENA

纵然是瞬间 提交于 2019-12-01 17:27:04

If you just want to restrict a variable to have a certain value for local queries you can do so with an overload of the QueryFactory.create() method which takes a QuerySolutionMap to set value restrictions. Note this doesn't alter your query just restricts the final results so this is not really parameterization.

If you want to actually have true parameterized queries (i.e. substitute variables for constants) then there are a couple of ways to do this depending on your version of ARQ.

Using any current release (up to 2.9.0) the only way to do it is string concatenation i.e. instead of having ?name in your query you would just insert the value you want e.g. "Bob"

Using the latest trunk (2.9.1-SNAPSHOT onwards) there is a new ParameterizedSparqlString class which makes this much more user friendly e.g.

ParameterizedSparqlString queryStr = new ParameterizedSparqlString(comNameQuery);
queryStr.setLiteral("name", "Bob");

Query query = QueryFactory.create(queryStr.toString());

And in fact you can simplify your code further since ParameterizedSparqlString has a StringBuffer style interface and can be used to build your query bit by bit and includes useful functionality like prepending prefixes to your query.

The advantage of this new method is that it provides a more generic way of doing parameterized queries that can also be used with updates and is usable for preparing remote queries which the existing methods do not cover.

You could try looking into Twinkql. It is a SPARQL-to-Java mapping framework. It uses Jena in the back end, but tries to simplify SPARQL queries and Java binding of the results.

It allows you to define SPARQL queries in xml:

<select id="getNovel" resultMap="novelResultMap">
<![CDATA[
    SELECT ?novel ?author
    WHERE {
        ?novel a <http://dbpedia.org/class/yago/EnglishNovels> ;
            <http://dbpedia.org/property/name> "#{novelName}"@en ;
            <http://dbpedia.org/property/author> ?author .
    }
]]>
</select>

Note the #{novelName} placeholder -- this is where parameters can be passed in at query time.

Also, results can be bound to Java Beans:

<resultMap id="novelResultMap" resultClass="org.twinkql.example.Novel">
    <uniqueResult>novel</uniqueResult>
    <rowMap  var="novel" varType="localName" beanProperty="name" />
    <rowMap var="author" varType="localName" beanProperty="author"/>
</resultMap>

There is an API to call these queries, to pass in parameters, etc. It is much like MyBatis, but for SPARQL instead of SQL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!