-
Notifications
You must be signed in to change notification settings - Fork 16
Query result mapping
Query results can be mapped to objects in a couple of ways.
Note that currently only SPARQL queries are supported.
By default, TypedQuery
results are directly mapped to entities. The query should select only the entity IRI, JOPA will take care of loading the corresponding entity based on the query result type.
A find all query can thus look like this:
List<Person> = em.createNativeQuery("SELECT ?x WHERE { ?x a foaf:Person . }", Person.class).getResultList();
TypedQuery
results can be also mapped to other, non-entity types. This mainly applies to primitive type wrappers, String
or identifier types - URI
and URL
.
An example is a ASK query result mapping:
Boolean exists = em.createNativeQuery("ASK { ?x a foaf:Person . }", Boolean.class).getSingleResult();
JOPA also allows to map query results to non-entity objects or provide a custom mapping where, for example, object attributes can be fetched directly in the query. This is achieved using the SparqlResultSetMapping
annotation, which works similarly to SqlResultSetMapping
in JPA.
For instance, using a constructor mapping, an object can be constructed from the query projection variables by using the following mapping:
@SparqlResultSetMapping(name = "RdfsResource",
classes = {@ConstructorResult(targetClass = RdfsResource.class,
variables = {
@VariableResult(name = "uri", type = URI.class),
@VariableResult(name = "label", type = String.class),
@VariableResult(name = "comment", type = String.class)})})
A corresponding constructor must exist in the target class:
public RdfsResource(URI uri, String label, String comment) {
this.uri = uri;
this.label = label;
this.comment = comment;
}
Other means of using SparqlResultSetMapping
include mapping to entities and variable mapping, again, similar to JPA. More info can be found in Javadoc.