I am trying to discover whether I had a specific resource in the model. For that I am using:
model.getResource("example")
Checking the doc, this method behaves exactly as createResource. Then, even if it is not in the model, I will get a new resource.
How can I check I have the resource avoiding its creation when it's not?
Thanks in advance!
In Jena, Resource
objects by themselves are not in the model. The model only contains triples - Statement
objects containing a subject, predicate and object (usually abbreviated SPO). Any one of S, P or O can be a resource (noting that a Property
is a sub-type of Resource
in Jena and in the RDF standard). So you need to refine your question from "does this model contain this resource" to either:
does model M contain resource R as a subject?
does model M contain resource R as a subject, predicate or object?
This can be achieved as:
Resource r = ... ;
Model m = ... ;
// does m contain r as a subject?
if (m.contains( r, null, (RDFNode) null )) {
..
}
// does m contain r as s, p or o?
if (m.containsResource( r )) {
..
}
Incidentally, in your code sample you have
model.getResource("example")
This returns a Resource
object corresponding to the given URI, but does not side-effect the triples in the model. This is the reason that Model
has both getResource
and createResource
- get is potentially slightly more efficient since it re-uses resource objects, but the semantics are essentially identical. However, the argument you pass to getResource
or createResource
should be a URI. You are borrowing trouble from the future if you start using tokens like "example"
in place of full URI's, so I would advise stopping this bad habit before you get comfortable with it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With