How to build SPARQL queries in java?

Martin Schlagnitweit picture Martin Schlagnitweit · Aug 30, 2011 · Viewed 14.3k times · Source

Is there a library, which is able to build SPARQL queries programmatically like the CriteriaBuilder in JPA or to build the queries like with a PreparedStatement for SQL?

Similar (for SQL): Cleanest way to build an SQL string in Java

Answer

RobV picture RobV · Dec 7, 2012

The recent versions of Jena have added a StringBuilder style API for building query/update strings and parameterizing them if desired.

This class is called ParameterizedSparqlString, here's an example of using it to create a query:

ParameterizedSparqlString queryStr = new ParameterizedSparqlString();
queryStr.setNSPrefix("sw", "http://skunkworks.example.com/redacted#");
queryStr.append("SELECT ?a ?b ?c ?d");
queryStr.append("{");
queryStr.append("   ?rawHit sw:key");
queryStr.appendNode(someKey);
queryStr.append(".");
queryStr.append("  ?rawHit sw:a ?a .");
queryStr.append("  ?rawHit sw:b ?b .");
queryStr.append("  ?rawHit sw:c ?c . ");
queryStr.append("  ?rawHit sw:d ?d .");
queryStr.append("} ORDER BY DESC(d)");

Query q = queryStr.asQuery();

Disclaimer - I'm the developer who contributed this functionality to Jena

See What's the best way to parametize SPARQL queries? for more discussion on doing this across various APIs.