Parameterized SPARQL query with JENA

前端 未结 2 1793
梦谈多话
梦谈多话 2021-01-18 04:30

I\'m trying to build a small semantic web application using Jena framework, JSP and JAVA. I have a remote SPARQL endpoint and I\'ve already written a simple query which work

相关标签:
2条回答
  • 2021-01-18 04:49

    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.

    0 讨论(0)
  • 2021-01-18 04:52

    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.

    0 讨论(0)
提交回复
热议问题