Reputation: 469
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!
Upvotes: 7
Views: 3861
Reputation: 13305
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!
Upvotes: 12
Reputation: 469
After researching a little bit I have found the next way. I don't know if this is really the best way to achieve it, but works:
Resource toSearch = ResourceFactory.createResource("example");
if(!model.containsResource(toSearch))...;
Upvotes: 3