I'm trying to tidy up some code that I currently have an make it a bit more generic. Currently I've a StringBuilder that works but I'd like to convert this into a SelectBuilder object so that I may pass in different subjects and the like from other functions and not nbeed to write the same code again.
I can pass in the String but I was hoping on using the jena.SelectBuilder as it looks tidy.
This is currently what I'm working on, ideally I'd like to be able to pass in the name and have that variable set, as well as the birthday (perhaps I could look for birthPlace instead)
The version below works, in that it returns ALL the birthdays but it is not returning the single birthday that I want', that of TonyBlair.
I realise that perhaps the question isn't clear - How can I pass in the value 'Tony_Blair' so that the '?name' value in the query is replaced with this string and gives me back the single result I want? I plan on being able to pass in ANY subject and/or predicate.
String name = "Tony_Blair";
SelectBuilder sbi = new SelectBuilder()
.addPrefix("dbr", "http://dbpedia.org/resource/")
.addPrefix("dbp", "http://dbpedia.org/property/")
.addPrefix("dbo", "http://dbpedia.org/ontology/")
//.addVar( "*" ) //the name?
//.addWhere( "dbr:Tony_Blair", "dbp:birthDate", "?dob" );
//.addWhere( "dbr:"+name, "dbp:birthDate", "?dob" );
.addWhere( "?name", "dbp:birthDate", "?dob" );
sbi.setVar(Var.alloc("?name"), NodeFactory.createLiteral("dbr:Tony_Blair"));
Query q = sbi.build() ;
This is the old version
StringBuilder sb = new StringBuilder();
sb.append("PREFIX dbr: <http://dbpedia.org/resource/> \n");
sb.append("PREFIX dbp: <http://dbpedia.org/property/> \n");
sb.append("PREFIX dbo: <http://dbpedia.org/ontology/> \n");
sb.append("SELECT (STR(?dob) as ?date_of_birth) \n");
sb.append("WHERE {dbr:Tony_Blair dbp:birthDate ?dob} \n");
Pass the variable name to Var.alloc
without the '?', it is added automatically. Also, as @AKSW stated in his comment, since dbr:Tony_Blair
is a URI, the call should be:
sbi.setVar(Var.alloc("name"), NodeFactory.createURI("dbr:Tony_Blair"));