Skip to content

Commit

Permalink
Enable HibernateHints.HINT_READ_ONLY hint to count() queries
Browse files Browse the repository at this point in the history
This adds the HibernateHints.HINT_READ_ONLY to the `count()` calls.
`count()` named queries are only set when the hint is not set through the `@NamedQuery` annotation

- Fixes quarkusio#35978
  • Loading branch information
gastaldi committed Sep 19, 2023
1 parent 3bf8a5a commit 8f57724
Showing 1 changed file with 14 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import jakarta.transaction.TransactionManager;

import org.hibernate.Session;
import org.hibernate.jpa.HibernateHints;

import io.agroal.api.AgroalDataSource;
import io.quarkus.agroal.DataSource;
Expand Down Expand Up @@ -320,20 +321,26 @@ public Stream<?> streamAll(Class<?> entityClass, Sort sort) {
public long count(Class<?> entityClass) {
return (long) getEntityManager(entityClass)
.createQuery("SELECT COUNT(*) FROM " + PanacheJpaUtil.getEntityName(entityClass))
.setHint(HibernateHints.HINT_READ_ONLY, true)
.getSingleResult();
}

public long count(Class<?> entityClass, String panacheQuery, Object... params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
Query namedQuery = extractNamedQuery(entityClass, panacheQuery);
if (!namedQuery.getHints().containsKey(HibernateHints.HINT_READ_ONLY)) {
namedQuery.setHint(HibernateHints.HINT_READ_ONLY, true);
}
return (long) bindParameters(namedQuery, params).getSingleResult();
}

try {
return (long) bindParameters(
getEntityManager(entityClass)
.createQuery(PanacheJpaUtil.createCountQuery(entityClass, panacheQuery, paramCount(params))),
params).getSingleResult();
params)
.setHint(HibernateHints.HINT_READ_ONLY, true)
.getSingleResult();
} catch (IllegalArgumentException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
Expand All @@ -342,14 +349,19 @@ public long count(Class<?> entityClass, String panacheQuery, Object... params) {
public long count(Class<?> entityClass, String panacheQuery, Map<String, Object> params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
Query namedQuery = extractNamedQuery(entityClass, panacheQuery);
if (!namedQuery.getHints().containsKey(HibernateHints.HINT_READ_ONLY)) {
namedQuery.setHint(HibernateHints.HINT_READ_ONLY, true);
}
return (long) bindParameters(namedQuery, params).getSingleResult();
}

try {
return (long) bindParameters(
getEntityManager(entityClass)
.createQuery(PanacheJpaUtil.createCountQuery(entityClass, panacheQuery, paramCount(params))),
params).getSingleResult();
params)
.setHint(HibernateHints.HINT_READ_ONLY, true)
.getSingleResult();
} catch (IllegalArgumentException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
Expand Down

0 comments on commit 8f57724

Please sign in to comment.