You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openjpa.apache.org by rz...@apache.org on 2026/08/20 10:46:50 UTC
(openjpa) 02/03: [OPENJPA-2985] Implement EntityManagerFactory.getNamedQueries(Class)
This is an automated email from the ASF dual-hosted git repository.
rzo1 pushed a commit to branch OPENJPA-2985
in repository https://gitbox.apache.org/repos/asf/openjpa.git
commit 7c8df6d949d939d5c7a8a3cecb0bcf947c859448
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Thu Aug 20 12:33:29 2026 +0200
[OPENJPA-2985] Implement EntityManagerFactory.getNamedQueries(Class)
EntityManagerFactoryImpl.getNamedQueries(Class) no longer throws
UnsupportedOperationException. It now forces loading of the persistent
types (mirroring the private MetaDataRepository.resolveAll() that
getQueryMetaData() uses, so a cold repository does not yield an empty
result), iterates the query metadata and returns a freshly built map of
TypedQueryReference for every named query whose declared result type is
assignable to the requested type. The declared result type is
QueryMetaData.getResultType(), falling back to getCandidateType(), which
makes the predicate exactly "createNamedQuery(name, resultType) is
legal". Named queries without any declared result type are never
returned, for any type including Object.class. The returned map is a
copy; each reference carries the query name, the result type and an
unmodifiable copy of the query hints. A null result type is rejected
with IllegalArgumentException and a closed factory raises the usual
IllegalStateException.
For this to be answerable from metadata,
AnnotationPersistenceMetaDataParser.parseNamedQueries() now honours the
JPA 3.2 @NamedQuery.resultClass() the same way parseNamedNativeQueries()
already honours @NamedNativeQuery.resultClass(): a managed result class
is stored as the candidate type, any other non-void class as the result
type. This is the identical branch that QueryImpl.setResultClass()
performs for createNamedQuery(name, resultClass), so behaviour matches
an explicit result class at the call site; note that setting the
candidate type also makes JPQLExpressionBuilder skip its own candidate
inference, which is the same situation as today's
createNamedQuery(name, X.class).
XMLPersistenceMetaDataParser is deliberately untouched: the bundled
orm_3_2.xsd.rsrc declares only a "name" attribute on <named-query>, so a
"result-class" attribute would fail schema validation before reaching
the parser. Refreshing the schema is left to a separate issue; until
then XML-declared named queries have no declared result type and are
therefore not returned by getNamedQueries().
New TypedQueryReferenceImpl is an immutable TypedQueryReference with
equals/hashCode/toString.
Tested by the new TestGetNamedQueries (with NamedQueryRefEntity, which
declares named queries with an entity resultClass plus a hint, a scalar
resultClass, no resultClass, and a native query with a resultClass):
covers the parser change, entity/scalar/supertype lookups, exclusion of
untyped queries, hints and their immutability, the returned map being a
copy, null argument handling, a cold second factory, addNamedQuery(), and
round-tripping a reference through EntityManager.createQuery().
---
.../persistence/query/NamedQueryRefEntity.java | 70 +++++++++
.../persistence/query/TestGetNamedQueries.java | 161 +++++++++++++++++++++
.../AnnotationPersistenceMetaDataParser.java | 8 +
.../persistence/EntityManagerFactoryImpl.java | 71 ++++++++-
.../persistence/TypedQueryReferenceImpl.java | 99 +++++++++++++
5 files changed, 408 insertions(+), 1 deletion(-)
diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/NamedQueryRefEntity.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/NamedQueryRefEntity.java
new file mode 100644
index 000000000..6ec45c7bd
--- /dev/null
+++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/NamedQueryRefEntity.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.query;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.NamedNativeQuery;
+import jakarta.persistence.NamedQueries;
+import jakarta.persistence.NamedQuery;
+import jakarta.persistence.QueryHint;
+import jakarta.persistence.Table;
+
+/**
+ * Entity declaring named queries with and without a JPA 3.2 {@code resultClass}.
+ */
+@Entity
+@Table(name = "NQ_REF_ENTITY")
+@NamedQueries({
+ @NamedQuery(name = "NQRef.all",
+ query = "select o from NamedQueryRefEntity o",
+ resultClass = NamedQueryRefEntity.class,
+ hints = @QueryHint(name = "openjpa.FetchPlan.MaxFetchDepth", value = "2")),
+ @NamedQuery(name = "NQRef.names",
+ query = "select o.name from NamedQueryRefEntity o",
+ resultClass = String.class),
+ @NamedQuery(name = "NQRef.untyped",
+ query = "select o from NamedQueryRefEntity o where o.name = 'x'")
+})
+@NamedNativeQuery(name = "NQRef.native",
+ query = "select id, name from NQ_REF_ENTITY",
+ resultClass = NamedQueryRefEntity.class)
+public class NamedQueryRefEntity {
+
+ @Id
+ private int id;
+
+ private String name;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestGetNamedQueries.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestGetNamedQueries.java
new file mode 100644
index 000000000..10a8306d1
--- /dev/null
+++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/query/TestGetNamedQueries.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.query;
+
+import java.util.Map;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.Query;
+import jakarta.persistence.TypedQueryReference;
+
+import org.apache.openjpa.meta.MetaDataRepository;
+import org.apache.openjpa.meta.QueryMetaData;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI;
+import org.apache.openjpa.persistence.test.SingleEMFTestCase;
+
+/**
+ * Tests the JPA 3.2 {@code EntityManagerFactory.getNamedQueries(Class)} and the
+ * {@code @NamedQuery.resultClass()} support it relies on.
+ */
+public class TestGetNamedQueries extends SingleEMFTestCase {
+
+ @Override
+ public void setUp() {
+ setUp(NamedQueryRefEntity.class, CLEAR_TABLES);
+ }
+
+ /**
+ * Regression test for @NamedQuery.resultClass() being parsed at all.
+ */
+ public void testAnnotationResultClassParsed() {
+ MetaDataRepository mdr = emf.getConfiguration().getMetaDataRepositoryInstance();
+
+ QueryMetaData all = mdr.getQueryMetaData(null, "NQRef.all", null, true);
+ assertEquals(NamedQueryRefEntity.class, all.getCandidateType());
+ assertNull(all.getResultType());
+
+ QueryMetaData names = mdr.getQueryMetaData(null, "NQRef.names", null, true);
+ assertEquals(String.class, names.getResultType());
+ assertNull(names.getCandidateType());
+
+ // resultClass() defaults to void.class - it must not leak into the metadata
+ QueryMetaData untyped = mdr.getQueryMetaData(null, "NQRef.untyped", null, true);
+ assertNull(untyped.getCandidateType());
+ assertNull(untyped.getResultType());
+ }
+
+ public void testEntityResultType() {
+ Map<String, TypedQueryReference<NamedQueryRefEntity>> refs =
+ emf.getNamedQueries(NamedQueryRefEntity.class);
+ assertTrue(refs.containsKey("NQRef.all"));
+ assertTrue(refs.containsKey("NQRef.native"));
+ assertFalse(refs.containsKey("NQRef.names"));
+ assertFalse(refs.containsKey("NQRef.untyped"));
+
+ TypedQueryReference<NamedQueryRefEntity> ref = refs.get("NQRef.all");
+ assertEquals("NQRef.all", ref.getName());
+ assertEquals(NamedQueryRefEntity.class, ref.getResultType());
+ }
+
+ public void testScalarResultType() {
+ Map<String, TypedQueryReference<String>> refs = emf.getNamedQueries(String.class);
+ assertTrue(refs.containsKey("NQRef.names"));
+ assertEquals(String.class, refs.get("NQRef.names").getResultType());
+ assertFalse(refs.containsKey("NQRef.all"));
+ assertFalse(refs.containsKey("NQRef.untyped"));
+ }
+
+ /**
+ * Queries without a declared result type are never returned - not even for Object.class.
+ */
+ public void testSupertypeIsAssignable() {
+ Map<String, TypedQueryReference<Object>> refs = emf.getNamedQueries(Object.class);
+ assertTrue(refs.containsKey("NQRef.all"));
+ assertTrue(refs.containsKey("NQRef.names"));
+ assertTrue(refs.containsKey("NQRef.native"));
+ assertFalse(refs.containsKey("NQRef.untyped"));
+ }
+
+ public void testHints() {
+ Map<String, Object> hints = emf.getNamedQueries(NamedQueryRefEntity.class)
+ .get("NQRef.all").getHints();
+ assertEquals("2", hints.get("openjpa.FetchPlan.MaxFetchDepth"));
+ try {
+ hints.put("x", "y");
+ fail("hints must be unmodifiable");
+ } catch (UnsupportedOperationException expected) {
+ // expected
+ }
+ }
+
+ public void testReturnedMapIsACopy() {
+ Map<String, TypedQueryReference<NamedQueryRefEntity>> refs =
+ emf.getNamedQueries(NamedQueryRefEntity.class);
+ refs.clear();
+ assertTrue(emf.getNamedQueries(NamedQueryRefEntity.class).containsKey("NQRef.all"));
+ }
+
+ public void testNullResultTypeRejected() {
+ try {
+ emf.getNamedQueries(null);
+ fail("expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ // expected
+ }
+ }
+
+ /**
+ * getNamedQueries() must work as the very first operation on a factory, i.e. before any
+ * entity manager forced the metadata repository to load the persistent types.
+ */
+ public void testColdRepository() {
+ OpenJPAEntityManagerFactorySPI emf2 = createEMF(NamedQueryRefEntity.class);
+ try {
+ assertTrue(emf2.getNamedQueries(NamedQueryRefEntity.class).containsKey("NQRef.all"));
+ } finally {
+ closeEMF(emf2);
+ }
+ }
+
+ public void testDynamicallyAddedNamedQuery() {
+ EntityManager em = emf.createEntityManager();
+ try {
+ Query q = em.createQuery("select o from NamedQueryRefEntity o");
+ emf.addNamedQuery("NQRef.dyn", q);
+ assertTrue(emf.getNamedQueries(NamedQueryRefEntity.class).containsKey("NQRef.dyn"));
+ } finally {
+ em.close();
+ }
+ }
+
+ /**
+ * The declared result class must not break execution of the named queries.
+ */
+ public void testCreateNamedQueryWithDeclaredResultClassStillWorks() {
+ EntityManager em = emf.createEntityManager();
+ try {
+ assertNotNull(em.createNamedQuery("NQRef.all").getResultList());
+ assertNotNull(em.createNamedQuery("NQRef.names", String.class).getResultList());
+ assertNotNull(em.createQuery(emf.getNamedQueries(NamedQueryRefEntity.class)
+ .get("NQRef.all")).getResultList());
+ } finally {
+ em.close();
+ }
+ }
+}
diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java
index 72b1a5a14..7ab5207b0 100644
--- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java
+++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/AnnotationPersistenceMetaDataParser.java
@@ -2029,6 +2029,14 @@ public class AnnotationPersistenceMetaDataParser
meta = getRepository().addQueryMetaData(_cls, query.name());
meta.setLanguage(JPQLParser.LANG_JPQL);
meta.setQueryString(query.query());
+ // JPA 3.2 added @NamedQuery.resultClass(); handle it exactly like
+ // @NamedNativeQuery.resultClass() so that a declared result type is
+ // available from the metadata (and to EntityManagerFactory.getNamedQueries).
+ Class<?> res = query.resultClass();
+ if (ImplHelper.isManagedType(getConfiguration(), res))
+ meta.setCandidateType(res);
+ else if (!void.class.equals(res))
+ meta.setResultType(res);
for (QueryHint hint : query.hints())
meta.addHint(hint.name(), hint.value());
LockModeType lmt = processNamedQueryLockModeType(query);
diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
index 61df45688..1927ba33f 100644
--- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
+++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
@@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -92,6 +93,8 @@ public class EntityManagerFactoryImpl
private final java.util.concurrent.ConcurrentHashMap<String, EntityGraphImpl<?>>
_entityGraphs = new java.util.concurrent.ConcurrentHashMap<>();
private volatile boolean _entityGraphsInitialized;
+ private final Object _namedQueriesLock = new Object();
+ private volatile boolean _namedQueriesInitialized;
private transient Map<String, Object> properties;
private transient Map<String, Object> emEmptyPropsProperties;
@@ -926,9 +929,75 @@ public class EntityManagerFactoryImpl
return OpenJPAPersistenceUtil.getClass(this, entity);
}
+ /**
+ * Return the named queries whose declared result type is assignable to the given result type.
+ * <p>
+ * The declared result type of a query is {@link QueryMetaData#getResultType()} if set, otherwise
+ * {@link QueryMetaData#getCandidateType()} - managed result classes are recorded as the candidate
+ * type by the metadata parsers, exactly as {@code createNamedQuery(name, resultClass)} would do.
+ * Named queries without any declared result type (i.e. a JPQL {@code @NamedQuery} without
+ * {@code resultClass}, or a query declared in XML - the bundled orm_3_2 schema does not allow a
+ * {@code result-class} attribute on {@code named-query}) are never returned, for any result type
+ * including {@code Object.class}, because their result type cannot be proven.
+ * <p>
+ * The hints carried by the returned references are the hints of the named query, including the
+ * OpenJPA specific hints synthesized by the parsers (e.g. {@code openjpa.FetchPlan.ReadLockMode}
+ * derived from {@code @NamedQuery.lockMode()}); these are exactly the hints replayed by
+ * {@code createNamedQuery}.
+ * <p>
+ * A freshly computed, modifiable map is returned on every call; it is not a live view of the
+ * metadata repository.
+ */
@Override
+ @SuppressWarnings("unchecked")
public <R> Map<String, TypedQueryReference<R>> getNamedQueries(Class<R> resultType) {
- throw new UnsupportedOperationException("Not yet implemented (JPA 3.2)");
+ if (resultType == null) {
+ throw new IllegalArgumentException("resultType is required");
+ }
+ _factory.assertOpen();
+ loadQueryMetaData();
+ Map<String, TypedQueryReference<R>> result = new HashMap<>();
+ for (QueryMetaData qmd : getConfiguration().getMetaDataRepositoryInstance().getQueryMetaDatas()) {
+ Class<?> declared = qmd.getResultType();
+ if (declared == null) {
+ declared = qmd.getCandidateType();
+ }
+ if (declared == null || !resultType.isAssignableFrom(declared)) {
+ continue;
+ }
+ String[] keys = qmd.getHintKeys();
+ Object[] values = qmd.getHintValues();
+ Map<String, Object> hints = new LinkedHashMap<>();
+ for (int i = 0; i < keys.length && i < values.length; i++) {
+ hints.put(keys[i], values[i]);
+ }
+ result.put(qmd.getName(),
+ new TypedQueryReferenceImpl<>(qmd.getName(), (Class<? extends R>) declared, hints));
+ }
+ return result;
+ }
+
+ /**
+ * Force loading of all persistent types so that their named queries are registered in the
+ * metadata repository. Mirrors the private {@code MetaDataRepository.resolveAll()} that
+ * {@code getQueryMetaData(...)} uses for the same reason: on a cold repository
+ * {@code getQueryMetaDatas()} would otherwise return an empty array.
+ */
+ private void loadQueryMetaData() {
+ if (_namedQueriesInitialized) {
+ return;
+ }
+ synchronized (_namedQueriesLock) {
+ if (_namedQueriesInitialized) {
+ return;
+ }
+ MetaDataRepository mdr = getConfiguration().getMetaDataRepositoryInstance();
+ ClassLoader loader = getConfiguration().getClassResolverInstance().getClassLoader(null, null);
+ for (Class<?> cls : mdr.loadPersistentTypes(false, loader)) {
+ mdr.getMetaData(cls, loader, false);
+ }
+ _namedQueriesInitialized = true;
+ }
}
@Override
diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/TypedQueryReferenceImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/TypedQueryReferenceImpl.java
new file mode 100644
index 000000000..4bbc0ab64
--- /dev/null
+++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/TypedQueryReferenceImpl.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import jakarta.persistence.TypedQueryReference;
+
+/**
+ * Immutable implementation of the JPA 3.2 {@link TypedQueryReference}. Instances are handed out by
+ * {@link EntityManagerFactoryImpl#getNamedQueries(Class)} and can be passed back to
+ * {@link jakarta.persistence.EntityManager#createQuery(TypedQueryReference)}.
+ *
+ * @param <R> the result type of the referenced named query
+ *
+ * @since 4.2.0
+ */
+public class TypedQueryReferenceImpl<R> implements TypedQueryReference<R> {
+
+ private final String _name;
+ private final Class<? extends R> _resultType;
+ private final Map<String, Object> _hints;
+
+ /**
+ * Constructor.
+ *
+ * @param name the name of the named query, must not be null
+ * @param resultType the declared result type of the named query, must not be null
+ * @param hints the query hints, may be null or empty. A defensive, unmodifiable copy is taken.
+ */
+ public TypedQueryReferenceImpl(String name, Class<? extends R> resultType, Map<String, Object> hints) {
+ if (name == null)
+ throw new IllegalArgumentException("name is required");
+ if (resultType == null)
+ throw new IllegalArgumentException("resultType is required");
+ _name = name;
+ _resultType = resultType;
+ _hints = (hints == null || hints.isEmpty())
+ ? Collections.emptyMap()
+ : Collections.unmodifiableMap(new LinkedHashMap<>(hints));
+ }
+
+ @Override
+ public String getName() {
+ return _name;
+ }
+
+ @Override
+ public Class<? extends R> getResultType() {
+ return _resultType;
+ }
+
+ /**
+ * The hints declared for this named query. The returned map is unmodifiable.
+ */
+ @Override
+ public Map<String, Object> getHints() {
+ return _hints;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other)
+ return true;
+ if (!(other instanceof TypedQueryReferenceImpl))
+ return false;
+ TypedQueryReferenceImpl<?> o = (TypedQueryReferenceImpl<?>) other;
+ return _name.equals(o._name) && _resultType.equals(o._resultType) && _hints.equals(o._hints);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(_name, _resultType, _hints);
+ }
+
+ @Override
+ public String toString() {
+ return "TypedQueryReference[name=" + _name + ", resultType=" + _resultType.getName() + "]";
+ }
+}