如何修改Jena Java程序,将SPARQL单变量查询改为双变量并返回Java数组
Modified Jena Method to Return SPARQL Results as Java Array
Got it, let's tweak your existing Jena query method to run the requested SPARQL query and send back the results as a 2D Java array (each row holds a ?s and ?class pair). Here's the adjusted code and breakdown:
// Updated return type from void to Object[][] to return query results private Object[][] runQuery(String query, Model model) { String defaultNameSpace = "your-actual-namespace-uri"; // Replace with your real ESCO namespace List<Object[]> resultsList = new ArrayList<>(); // Build full query with required prefixes StringBuffer queryStr = new StringBuffer(); queryStr.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "); queryStr.append("PREFIX esco: <" + defaultNameSpace + "> "); queryStr.append(query); // Attach the incoming query string try { // Create and execute the SPARQL query Query sparqlQuery = QueryFactory.create(queryStr.toString()); // Use try-with-resources to auto-close QueryExecution and avoid leaks try (QueryExecution qexec = QueryExecutionFactory.create(sparqlQuery, model)) { ResultSet rs = qexec.execSelect(); // Loop through results and collect each ?s + ?class pair while (rs.hasNext()) { QuerySolution soln = rs.nextSolution(); // Extract URIs as strings (you can keep Resource objects if needed instead) String subjectUri = soln.getResource("s").getURI(); String classUri = soln.getResource("class").getURI(); resultsList.add(new Object[]{subjectUri, classUri}); } } } catch (QueryParseException e) { // Handle query parsing errors gracefully e.printStackTrace(); return new Object[0][0]; // Return empty array on failure } // Convert the list to a 2D Java array and return return resultsList.toArray(new Object[resultsList.size()][]); }
Key Adjustments Explained:
- Return Type Shift: Swapped
voidforObject[][]so we can pass back the query results. If you want a strictly typed array likeString[][], just adjust the array declarations accordingly. - Critical Prefix Addition: Added the
rdf:prefix since your query usesrdf:type—omitting this would cause parsing errors. - Result Collection: Used an
ArrayListto gather result pairs first (flexible for dynamic result counts), then converted it to a 2D array to meet your requirement. - Resource Safety: Used a try-with-resources block for
QueryExecutionto ensure it's properly closed after use, preventing resource leaks. - Error Handling: Added basic catch logic for query parsing issues, returning an empty array if something goes wrong.
How to Use the Updated Method:
Call it with your target query string like this:
String targetQuery = "select distinct ?s ?class where {?s rdf:type ?class }"; Object[][] queryResults = runQuery(targetQuery, yourJenaModel); // Iterate over the results to use them for (Object[] row : queryResults) { String subject = (String) row[0]; String clazz = (String) row[1]; System.out.printf("Subject: %s, Class: %s%n", subject, clazz); }
内容的提问来源于stack exchange,提问作者marco
相关产品推荐
相关产品推荐

