Skip to content

Commit 0d0340e

Browse files
committed
[Ref] Replace RDF4J usage in TermDao#countReferences with JOPA native query and hardcode skos:ConceptScheme to query string instead of parameter binding.
1 parent 939a633 commit 0d0340e

3 files changed

Lines changed: 24 additions & 59 deletions

File tree

‎src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
import cz.cvut.kbss.termit.model.util.EntityToOwlClassMapper;
2727
import cz.cvut.kbss.termit.model.util.HasIdentifier;
2828
import jakarta.annotation.Nonnull;
29-
import org.eclipse.rdf4j.repository.RepositoryConnection;
3029
import org.slf4j.Logger;
3130
import org.slf4j.LoggerFactory;
3231
import org.springframework.context.ApplicationEventPublisher;
@@ -166,24 +165,4 @@ protected Descriptor getDescriptor() {
166165
public void setApplicationEventPublisher(@Nonnull ApplicationEventPublisher eventPublisher) {
167166
this.eventPublisher = eventPublisher;
168167
}
169-
170-
/**
171-
* Unwraps the supplied entity manager to {@link RepositoryConnection} within the current active transaction.
172-
*
173-
* @param entityManager the entity manager to unwrap
174-
* @return open repository connection with active current transaction
175-
* @implSpec The connection is managed by the {@link EntityManager} and must not be used with try-auto-close statement.
176-
*/
177-
public static RepositoryConnection unwrapToConnection(EntityManager entityManager) {
178-
if (!entityManager.isOpen() || !entityManager.getTransaction().isActive()) {
179-
throw new IllegalStateException("Entity manager is not open(" + entityManager.isOpen() +
180-
") or there is no active transaction (" + entityManager.getTransaction().isActive() + ")!");
181-
}
182-
final RepositoryConnection connection = entityManager.unwrap(RepositoryConnection.class);
183-
if (connection != null && connection.isActive()) {
184-
return connection;
185-
}
186-
entityManager.createNativeQuery("ASK {}", Boolean.class).getSingleResult(); // force em to open a connection
187-
return Objects.requireNonNull(entityManager.unwrap(RepositoryConnection.class), "Failed to acquire repository connection");
188-
}
189168
}

‎src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java‎

Lines changed: 24 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@
4141
import cz.cvut.kbss.termit.model.Term;
4242
import cz.cvut.kbss.termit.model.TermInfoWithParents;
4343
import cz.cvut.kbss.termit.model.Vocabulary;
44-
import cz.cvut.kbss.termit.model.Vocabulary_;
4544
import cz.cvut.kbss.termit.model.util.HasIdentifier;
4645
import cz.cvut.kbss.termit.persistence.context.DescriptorFactory;
4746
import cz.cvut.kbss.termit.persistence.context.VocabularyContextMapper;
@@ -51,12 +50,10 @@
5150
import cz.cvut.kbss.termit.util.Configuration;
5251
import cz.cvut.kbss.termit.util.Utils;
5352
import org.eclipse.rdf4j.model.IRI;
54-
import org.eclipse.rdf4j.model.Literal;
5553
import org.eclipse.rdf4j.model.Resource;
5654
import org.eclipse.rdf4j.model.Statement;
5755
import org.eclipse.rdf4j.model.util.Values;
5856
import org.eclipse.rdf4j.query.BindingSet;
59-
import org.eclipse.rdf4j.query.Operation;
6057
import org.eclipse.rdf4j.query.TupleQuery;
6158
import org.eclipse.rdf4j.query.TupleQueryResult;
6259
import org.eclipse.rdf4j.repository.RepositoryConnection;
@@ -94,6 +91,9 @@ public class TermDao extends BaseAssetDao<Term> implements SnapshotProvider<Term
9491
/**
9592
* Matches triples where the term is an object in a vocabulary graph excluding vocabulary snapshots.
9693
* {@code skos:hasTopConcept} relations are excluded
94+
* @implNote Bindings are required in {@link #countReferences(AbstractTerm)},
95+
* {@link #findReferencesInternal(AbstractTerm, Pageable)}, {@link #removeReferencesTo(AbstractTerm)}
96+
* and {@link #referencesToTermExist(AbstractTerm)}
9797
*/
9898
private static final String REFERENCES_TO_TERM_WHERE_CLAUSE = """
9999
WHERE {
@@ -102,7 +102,7 @@ public class TermDao extends BaseAssetDao<Term> implements SnapshotProvider<Term
102102
?context a ?versionOfVocabulary .
103103
}
104104
?other ?relation ?term .
105-
?context a ?vocabulary .
105+
?context a <http://www.w3.org/2004/02/skos/core#ConceptScheme> .
106106
FILTER (?relation NOT IN (
107107
<http://www.w3.org/2004/02/skos/core#hasTopConcept>
108108
))
@@ -1330,7 +1330,6 @@ public boolean referencesToTermExist(AbstractTerm term) {
13301330
try {
13311331
return em.createNativeQuery("ASK " + REFERENCES_TO_TERM_WHERE_CLAUSE, Boolean.class)
13321332
.setParameter("term", term.getUri())
1333-
.setParameter("vocabulary", Vocabulary_.entityClassIRI)
13341333
.setParameter("versionOfVocabulary", URI.create(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary))
13351334
.getSingleResult();
13361335
} catch (RuntimeException e) {
@@ -1351,15 +1350,12 @@ public Page<Statement> findReferences(AbstractTerm term, Pageable pageable) {
13511350
Objects.requireNonNull(pageable, "Pageable cannot be null");
13521351

13531352
try {
1354-
RepositoryConnection con = unwrapToConnection(em);
1355-
// On purpose not using auto-closable with try statement to prevent closing the connection here
1356-
// the connection is managed by Entity Manager
1357-
final long totalCount = countReferences(con, term);
1353+
final long totalCount = countReferences(term);
13581354
if (totalCount == 0 || pageable.getOffset() >= totalCount) {
13591355
return new PageImpl<>(List.of(), pageable, totalCount);
13601356
}
13611357

1362-
final List<Statement> statements = findReferences(con, term, pageable);
1358+
final List<Statement> statements = findReferencesInternal(term, pageable);
13631359
return new PageImpl<>(statements, pageable, totalCount);
13641360
} catch (RuntimeException e) {
13651361
throw new PersistenceException("Failed to find references to term " + Utils.uriToString(term.getUri()), e);
@@ -1369,36 +1365,42 @@ public Page<Statement> findReferences(AbstractTerm term, Pageable pageable) {
13691365
/**
13701366
* Counts the total amount of references to the specified term
13711367
*
1372-
* @param con the repository connection
13731368
* @param term the term to which references should be counted
13741369
* @return the total number of statements referencing the term as object
13751370
*/
1376-
private long countReferences(RepositoryConnection con, AbstractTerm term) {
1377-
final TupleQuery countQuery = con.prepareTupleQuery(
1378-
"SELECT (COUNT(*) AS ?count) " + REFERENCES_TO_TERM_WHERE_CLAUSE);
1379-
bindReferencesQueryParameters(countQuery, term);
1380-
countQuery.setIncludeInferred(false);
1381-
try (TupleQueryResult result = countQuery.evaluate()) {
1382-
final BindingSet bindings = result.next();
1383-
return ((Literal) bindings.getValue("count")).longValue();
1371+
private long countReferences(AbstractTerm term) {
1372+
try {
1373+
return em.createNativeQuery("SELECT (COUNT(*) AS ?count) " + REFERENCES_TO_TERM_WHERE_CLAUSE, Long.class)
1374+
.setParameter("term", term.getUri())
1375+
.setParameter("versionOfVocabulary", cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)
1376+
.getSingleResult();
1377+
} catch (RuntimeException e) {
1378+
throw new PersistenceException("Failed to count references to term " + Utils.uriToString(term.getUri()), e);
13841379
}
13851380
}
13861381

13871382
/**
13881383
* Finds a page contents of references to the specified term.
13891384
*
1390-
* @param con the repository connection
13911385
* @param term the term to which references should be found
13921386
* @param pageable page spec
13931387
* @return the list of statements referencing the term as object
13941388
*/
1395-
private List<Statement> findReferences(RepositoryConnection con, AbstractTerm term, Pageable pageable) {
1389+
private List<Statement> findReferencesInternal(AbstractTerm term, Pageable pageable) {
1390+
// On purpose not using auto-closable with try statement to prevent closing the connection here
1391+
// the connection is managed by Entity Manager
1392+
final RepositoryConnection con = em.unwrap(RepositoryConnection.class);
1393+
// The connection is guaranteed to be open by first counting the total references count
13961394
final TupleQuery query = con.prepareTupleQuery(
13971395
"SELECT ?other ?relation ?term ?context " + REFERENCES_TO_TERM_WHERE_CLAUSE +
13981396
" ORDER BY ?other ?relation ?context" +
13991397
" OFFSET " + pageable.getOffset() +
14001398
" LIMIT " + pageable.getPageSize());
1401-
bindReferencesQueryParameters(query, term);
1399+
1400+
query.setBinding("term", Values.iri(term.getUri().toString()));
1401+
query.setBinding("versionOfVocabulary",
1402+
Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary));
1403+
14021404
query.setIncludeInferred(false);
14031405

14041406
final List<Statement> statements = new ArrayList<>(pageable.getPageSize());
@@ -1416,19 +1418,6 @@ private List<Statement> findReferences(RepositoryConnection con, AbstractTerm te
14161418
return statements;
14171419
}
14181420

1419-
/**
1420-
* Sets required query bindings for {@link #REFERENCES_TO_TERM_WHERE_CLAUSE}.
1421-
*
1422-
* @param query query operation
1423-
* @param term the term to which references should be found
1424-
*/
1425-
private void bindReferencesQueryParameters(Operation query, AbstractTerm term) {
1426-
query.setBinding("term", Values.iri(term.getUri().toString()));
1427-
query.setBinding("vocabulary", Values.iri(Vocabulary_.entityClassIRI.toString()));
1428-
query.setBinding("versionOfVocabulary",
1429-
Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary));
1430-
}
1431-
14321421
/**
14331422
* Removes all triples from vocabularies where the given term is references as object.
14341423
*
@@ -1446,7 +1435,6 @@ public void removeReferencesTo(AbstractTerm toRemove) {
14461435
}
14471436
""" + REFERENCES_TO_TERM_WHERE_CLAUSE)
14481437
.setParameter("term", toRemove.getUri())
1449-
.setParameter("vocabulary", Vocabulary_.entityClassIRI)
14501438
.setParameter("versionOfVocabulary", URI.create(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary))
14511439
.executeUpdate();
14521440
} catch (RuntimeException e) {

‎src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,6 @@ private void pruneAndNormalizeTranslations(Term instance) {
205205
@Override
206206
protected void postUpdate(@Nonnull Term instance) {
207207
final Vocabulary vocabulary = vocabularyService.findRequired(instance.getVocabulary());
208-
// Jopa should always set at least empty collection
209-
Objects.requireNonNull(vocabulary.getRootTerms(), "Vocabulary must have root terms collection");
210208
if (instance.hasParentInSameVocabulary()) {
211209
vocabulary.removeRootTerm(instance);
212210
} else {

0 commit comments

Comments
 (0)