This is an automated email from the ASF dual-hosted git repository.

zstan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ignite.git


The following commit(s) were added to refs/heads/master by this push:
     new f5001240d81 IGNITE-28907 Disallow mixing query entity configuration 
APIs and use last-call-wins semantics (#13583)
f5001240d81 is described below

commit f5001240d8120d1ffdece28884168498e572cf99
Author: oleg-vlsk <[email protected]>
AuthorDate: Tue Nov 3 22:37:33 2026 +1000

    IGNITE-28907 Disallow mixing query entity configuration APIs and use 
last-call-wins semantics (#13583)
---
 docs/_docs/SQL/indexes.adoc                        |  11 +
 docs/_docs/SQL/sql-api.adoc                        |  26 +
 docs/_docs/data-modeling/affinity-collocation.adoc |  11 +
 .../UnstableTopologyIntegrationTest.java           |   3 +-
 .../ignite/jdbc/thin/JdbcThinMetadataSelfTest.java |  42 --
 .../ignite/configuration/CacheConfiguration.java   | 141 ++--
 .../CacheConfigurationInternalAccessor.java        |  45 ++
 .../processors/cache/ClusterCachesInfo.java        |   4 +-
 .../internal/processors/cache/GridCacheUtils.java  |  20 +-
 .../cache/CacheConfigurationQueryEntityTest.java   | 716 +++++++++++++++++++++
 .../IgniteCacheAbstractInsertSqlQuerySelfTest.java |   6 +-
 .../cache/IgniteCacheAbstractQuerySelfTest.java    |  61 +-
 ...eCacheDuplicateEntityConfigurationSelfTest.java | 106 ---
 .../query/IgniteQueryDedicatedPoolTest.java        |   3 +-
 .../processors/query/RunningQueriesTest.java       |   1 -
 .../query/h2/sql/BaseH2CompareQueryTest.java       |   8 +-
 ...neOrSinglePartitionsQueryOptimizationsTest.java |   6 +-
 .../IgniteBinaryCacheQueryTestSuite6.java          |   4 +-
 .../indexed-types-then-query-entities.xml          |  46 ++
 .../query-entities-then-indexed-types.xml          |  46 ++
 .../CacheConfigurationQueryEntityXmlTest.java      |  85 +++
 .../ignite/testsuites/IgniteSpringTestSuite.java   |   3 +
 22 files changed, 1153 insertions(+), 241 deletions(-)

diff --git a/docs/_docs/SQL/indexes.adoc b/docs/_docs/SQL/indexes.adoc
index 9eaccf8a5c1..c014c46e094 100644
--- a/docs/_docs/SQL/indexes.adoc
+++ b/docs/_docs/SQL/indexes.adoc
@@ -159,6 +159,8 @@ tab:C++[unsupported]
 
 This method accepts only pairs of types: one for key class and another for 
value class. Primitives are passed as boxed types.
 
+In Java, repeated `CacheConfiguration.setIndexedTypes(...)` calls replace the 
previously registered types and query entities. To register multiple key/value 
type pairs, pass all pairs in the same call. Do not combine this method with 
`CacheConfiguration.setQueryEntities(...)` on the same configuration instance.
+
 [NOTE]
 ====
 [discrete]
@@ -197,6 +199,15 @@ Indexes and queryable fields can also be configured via 
the `org.apache.ignite.c
 
 All concepts that are discussed as part of the annotation based configuration 
above are also valid for the `QueryEntity` based approach. Furthermore, the 
types whose fields are configured with the `@QuerySqlField` annotation and are 
registered with the `CacheConfiguration.setIndexedTypes()` method are 
internally converted into query entities.
 
+[IMPORTANT]
+====
+The internal conversion does not allow combining the two Java configuration 
APIs. Calling both `setIndexedTypes(...)` and `setQueryEntities(...)` on the 
same `CacheConfiguration` throws `CacheException`.
+
+When using `setQueryEntities(...)`, provide the complete collection of query 
entities with all required index definitions. Repeated calls replace the 
collection rather than merge it.
+
+See link:SQL/sql-api#repeated-configuration-calls[Repeated Configuration 
Calls].
+====
+
 The example below shows how to define a single field index, group indexes, and 
queryable fields.
 
 [tabs]
diff --git a/docs/_docs/SQL/sql-api.adoc b/docs/_docs/SQL/sql-api.adoc
index 64c2d195e9b..2044ac0d523 100644
--- a/docs/_docs/SQL/sql-api.adoc
+++ b/docs/_docs/SQL/sql-api.adoc
@@ -35,6 +35,11 @@ In Java, queryable fields can be configured in two ways:
 * using annotations
 * by defining query entities
 
+[IMPORTANT]
+====
+For a Java `CacheConfiguration`, use either `setIndexedTypes(...)` or 
`setQueryEntities(...)`. Calling both methods on the same configuration 
instance throws `CacheException`, regardless of the call order. This also 
applies to the `indexedTypes` and `queryEntities` properties of a Spring XML 
cache configuration bean.
+====
+
 
 === @QuerySqlField Annotation
 
@@ -88,6 +93,27 @@ 
include::code-snippets/dotnet/UsingSqlApi.cs[tag=queryEntities,indent=0]
 tab:C++[unsupported]
 --
 
+=== Repeated Configuration Calls
+
+The Java `CacheConfiguration.setIndexedTypes(...)` and 
`CacheConfiguration.setQueryEntities(...)` methods use last-call-wins semantics 
when called repeatedly through the same API:
+
+* Each `setIndexedTypes(...)` call replaces the previously configured indexed 
types and query entities. Pass all required key/value type pairs in the same 
call.
+* Each `setQueryEntities(...)` call replaces the entire query entities 
collection, including entities with the same value type. Pass the complete 
collection in the final call.
+* Passing an empty array or `null` to `setIndexedTypes(...)` clears the 
indexed types and query entities.
+* Passing an empty collection or `null` to `setQueryEntities(...)` clears the 
query entities.
+
+An empty or `null` argument still selects the corresponding configuration API. 
Calling `clearQueryEntities()` does not reset that choice and does not allow 
switching between the two APIs.
+
+These setters configure the cache before creation. Calling them does not 
update the schema of an already running cache.
+
+When migrating existing configuration code:
+
+* Replace mixed `setIndexedTypes(...)` and `setQueryEntities(...)` calls with 
a single configuration API. If you use query entities, include all required 
fields and indexes in those entities.
+* Replace additive `setQueryEntities(...)` calls with one call containing the 
complete collection.
+* If a configuration helper receives no indexed types and is expected to leave 
SQL configuration unspecified, skip `setIndexedTypes(...)` rather than calling 
it with an empty array.
+
+Affinity key configurations have separate update rules; see 
link:data-modeling/affinity-collocation#configuring-affinity-with-indexed-types[Configuring
 Affinity with Indexed Types].
+
 == Querying
 
 To execute a select query on a cache, simply create an object of 
`SqlFieldsQuery` providing the query string to the constructor and run 
`cache.query(...)`.
diff --git a/docs/_docs/data-modeling/affinity-collocation.adoc 
b/docs/_docs/data-modeling/affinity-collocation.adoc
index f7591d12b62..7d902e36c34 100644
--- a/docs/_docs/data-modeling/affinity-collocation.adoc
+++ b/docs/_docs/data-modeling/affinity-collocation.adoc
@@ -126,3 +126,14 @@ 
include::{dotnetSourceFile}[tag=affinity-key-class,indent=0]
 ----
 tab:C++[unsupported]
 --
+
+[[configuring-affinity-with-indexed-types]]
+== Configuring Affinity with Indexed Types
+
+In Java, `CacheConfiguration.setIndexedTypes(...)` also derives affinity key 
configurations from `@AffinityKeyMapped` annotations on the supplied key types.
+
+Each derived configuration replaces any existing `CacheKeyConfiguration` for 
the same type, including one explicitly supplied through 
`setKeyConfiguration(...)`. Configurations for other types are preserved, 
including those derived from earlier `setIndexedTypes(...)` calls.
+
+If no affinity mapping is derived for a type, its existing configuration is 
preserved. Passing an empty array or `null` to `setIndexedTypes(...)` does not 
remove affinity key configurations.
+
+If you need explicit affinity settings to override annotation-derived 
settings, call `setKeyConfiguration(...)` after `setIndexedTypes(...)`. Note 
that `setKeyConfiguration(...)` replaces the entire key configuration array, so 
include all required mappings in that call.
\ No newline at end of file
diff --git 
a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/UnstableTopologyIntegrationTest.java
 
b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/UnstableTopologyIntegrationTest.java
index 834e1283963..2bfa74e0373 100644
--- 
a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/UnstableTopologyIntegrationTest.java
+++ 
b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/UnstableTopologyIntegrationTest.java
@@ -118,8 +118,7 @@ public class UnstableTopologyIntegrationTest extends 
AbstractBasicIntegrationTes
             .setSqlSchema(POI_SCHEMA_NAME)
             .setQueryEntities(Collections.singletonList(queryEntity()))
             
.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC)
-            .setCacheMode(CacheMode.PARTITIONED)
-            .setIndexedTypes(Integer.class, Integer.class));
+            .setCacheMode(CacheMode.PARTITIONED));
 
         cfg.setClusterStateOnStart(ClusterState.ACTIVE);
 
diff --git 
a/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinMetadataSelfTest.java
 
b/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinMetadataSelfTest.java
index 1d3686450a1..0c4acd17469 100644
--- 
a/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinMetadataSelfTest.java
+++ 
b/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinMetadataSelfTest.java
@@ -68,7 +68,6 @@ import static 
org.apache.ignite.internal.processors.query.QueryUtils.KEY_FIELD_N
 import static 
org.apache.ignite.internal.processors.query.QueryUtils.SCHEMA_SYS;
 import static 
org.apache.ignite.internal.processors.query.QueryUtils.VAL_FIELD_NAME;
 import static 
org.apache.ignite.internal.processors.query.schema.management.SchemaManager.SQL_IDXS_VIEW;
-import static org.apache.ignite.internal.util.lang.GridFunc.asMap;
 
 /**
  * Metadata tests.
@@ -244,47 +243,6 @@ public class JdbcThinMetadataSelfTest extends 
JdbcThinAbstractSelfTest {
         }
     }
 
-    /**
-     * Ensure metadata returned for cache with explicit query entities has no 
duplicate columns: <ul>
-     *     <li>create a cache with indexed types and explicit query entity</li>
-     *     <li>request metadata for columns from the cache</li>
-     *     <li>verify returned result</li>
-     * </ul>
-     *
-     * @throws SQLException
-     */
-    @Test
-    public void testMetadataNotDublicatedIfFieldsSetExplicitly() throws 
SQLException {
-        final String cacheName = "testCache";
-
-        IgniteCache<?, ?> cache = grid(0).createCache(
-            new CacheConfiguration<>(cacheName)
-                .setQueryEntities(Collections.singleton(
-                    new QueryEntity()
-                        .setKeyType(Integer.class.getName())
-                        .setKeyFieldName("my_key")
-                        .setValueType(String.class.getName())
-                        .setFields(new LinkedHashMap<>(asMap("my_key", 
Integer.class.getName())))
-                ))
-                .setIndexedTypes(Integer.class, String.class)
-        );
-
-        try (Connection conn = DriverManager.getConnection(URL)) {
-            DatabaseMetaData meta = conn.getMetaData();
-
-            ResultSet rs = meta.getColumns(null, cacheName, null, null);
-
-            assertTrue(rs.next());
-            assertEquals(cacheName, 
rs.getString(MetadataColumn.TABLE_SCHEMA.columnName()));
-            assertEquals("MY_KEY", 
rs.getString(MetadataColumn.COLUMN_NAME.columnName()));
-
-            assertFalse(rs.next());
-        }
-        finally {
-            cache.destroy();
-        }
-    }
-
     /**
      * @throws Exception If failed.
      */
diff --git 
a/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
 
b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
index ce1bc69c9b7..995ba34a66a 100644
--- 
a/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
+++ 
b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
@@ -22,6 +22,8 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
 import java.util.Objects;
 import javax.cache.Cache;
 import javax.cache.CacheException;
@@ -174,6 +176,10 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
     /** Default disk page compression algorithm. */
     public static final DiskPageCompression DFLT_DISK_PAGE_COMPRESSION = 
DiskPageCompression.DISABLED;
 
+    /** Error message template for configuring query entities through both 
setIndexedTypes and setQueryEntities. */
+    public static final String MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE =
+        "Query entities can be configured either with setIndexedTypes or 
setQueryEntities, but not both [cacheName=%s]";
+
     /** Cache name. */
     private String name;
 
@@ -358,6 +364,9 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
     /** Query entities. */
     private Collection<QueryEntity> qryEntities;
 
+    /** API used to configure query entities in this configuration instance. */
+    private transient QueryEntityConfigurationSource qryEntityCfgSrc;
+
     /** Partition loss policy. */
     private PartitionLossPolicy partLossPlc = DFLT_PARTITION_LOSS_POLICY;
 
@@ -469,6 +478,7 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
         pluginCfgs = cc.getPluginConfigurations();
         qryDetailMetricsSz = cc.getQueryDetailMetricsSize();
         qryEntities = cc.getQueryEntities() == 
Collections.<QueryEntity>emptyList() ? null : cc.getQueryEntities();
+        qryEntityCfgSrc = cc.qryEntityCfgSrc;
         qryParallelism = cc.getQueryParallelism();
         readFromBackup = cc.isReadFromBackup();
         rebalanceBatchSize = cc.getRebalanceBatchSize();
@@ -1933,25 +1943,39 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
      * <p>
      * To expose fields of these types onto SQL level and to index them you 
have to use annotations
      * from package {@link org.apache.ignite.cache.query.annotations}.
+     * <p>
+     * This method must not be used together with {@link #setQueryEntities}.
+     * <p>
+     * Repeated calls replace the indexed types and query entities configured 
by the previous call.
+     * Passing an empty array or {@code null} clears the indexed types and 
query entities.
+     * <p>
+     * Key configurations derived from affinity annotations replace existing 
key configurations
+     * for the same types or are added if none exist. Key configurations for 
other types are preserved,
+     * including those derived from previous calls. Passing an empty array or 
{@code null} leaves key configurations
+     * unchanged.
      *
      * @param indexedTypes Key and value type pairs.
      * @return {@code this} for chaining.
+     * @throws CacheException If query entities have already been configured 
through {@link #setQueryEntities}.
      */
     public CacheConfiguration<K, V> setIndexedTypes(Class<?>... indexedTypes) {
-        if (F.isEmpty(indexedTypes))
-            return this;
+        
checkQueryEntityConfigurationSource(QueryEntityConfigurationSource.INDEXED_TYPES);
 
-        int len = indexedTypes.length;
+        if (F.isEmpty(indexedTypes)) {
+            this.indexedTypes = new Class<?>[0];
+
+            qryEntities = new ArrayList<>();
+
+            qryEntityCfgSrc = QueryEntityConfigurationSource.INDEXED_TYPES;
 
-        if (len == 0)
             return this;
+        }
+
+        int len = indexedTypes.length;
 
         A.ensure((len & 1) == 0,
             "Number of indexed types is expected to be even. Refer to method 
javadoc for details.");
 
-        if (this.indexedTypes != null)
-            throw new CacheException("Indexed types can be set only once.");
-
         Class<?>[] newIndexedTypes = new Class<?>[len];
 
         for (int i = 0; i < len; i++) {
@@ -1961,8 +1985,14 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
             newIndexedTypes[i] = U.box(indexedTypes[i]);
         }
 
-        if (qryEntities == null)
-            qryEntities = new ArrayList<>();
+        Collection<QueryEntity> newQryEntities = new ArrayList<>();
+
+        Map<String, CacheKeyConfiguration> newKeyCfgs = new LinkedHashMap<>();
+
+        if (keyCfg != null) {
+            for (CacheKeyConfiguration keyConfiguration : keyCfg)
+                newKeyCfgs.put(keyConfiguration.getTypeName(), 
keyConfiguration);
+        }
 
         for (int i = 0; i < len; i += 2) {
             Class<?> keyCls = newIndexedTypes[i];
@@ -1972,7 +2002,7 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
 
             boolean dup = false;
 
-            for (QueryEntity entity : qryEntities) {
+            for (QueryEntity entity : newQryEntities) {
                 if (Objects.equals(entity.findValueType(), 
newEntity.findValueType())) {
                     dup = true;
 
@@ -1981,7 +2011,7 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
             }
 
             if (!dup)
-                qryEntities.add(newEntity);
+                newQryEntities.add(newEntity);
 
             // Set key configuration if needed.
             String affFieldName = BinaryUtils.affinityFieldName(keyCls);
@@ -1989,31 +2019,17 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
             if (affFieldName != null) {
                 CacheKeyConfiguration newKeyCfg = new 
CacheKeyConfiguration(newEntity.getKeyType(), affFieldName);
 
-                if (F.isEmpty(keyCfg))
-                    keyCfg = new CacheKeyConfiguration[] { newKeyCfg };
-                else {
-                    boolean keyCfgDup = false;
-
-                    for (CacheKeyConfiguration oldKeyCfg : keyCfg) {
-                        if (Objects.equals(oldKeyCfg.getTypeName(), 
newKeyCfg.getTypeName())) {
-                            keyCfgDup = true;
-
-                            break;
-                        }
-                    }
+                newKeyCfgs.put(newKeyCfg.getTypeName(), newKeyCfg);
+            }
+        }
 
-                    if (!keyCfgDup) {
-                        CacheKeyConfiguration[] keyCfg0 = new 
CacheKeyConfiguration[keyCfg.length + 1];
+        this.indexedTypes = newIndexedTypes;
 
-                        System.arraycopy(keyCfg, 0, keyCfg0, 0, keyCfg.length);
+        qryEntities = newQryEntities;
 
-                        keyCfg0[keyCfg0.length - 1] = newKeyCfg;
+        keyCfg = newKeyCfgs.isEmpty() ? null : newKeyCfgs.values().toArray(new 
CacheKeyConfiguration[0]);
 
-                        keyCfg = keyCfg0;
-                    }
-                }
-            }
-        }
+        qryEntityCfgSrc = QueryEntityConfigurationSource.INDEXED_TYPES;
 
         return this;
     }
@@ -2075,42 +2091,38 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
 
     /**
      * Sets query entities configuration.
+     * <p>
+     * This method must not be used together with {@link #setIndexedTypes}.
+     * <p>
+     * Repeated calls replace the query entities configured by the previous 
call.
+     * Passing an empty collection or {@code null} clears the existing query 
entities.
      *
-     * @param qryEntities Query entities.
+     * @param qryEntities qryEntities Query entities, or {@code null} to clear 
the existing query entities.
      * @return {@code this} for chaining.
+     * @throws CacheException If query entities have already been configured 
through {@link #setIndexedTypes}.
      */
-    public CacheConfiguration<K, V> setQueryEntities(Collection<QueryEntity> 
qryEntities) {
-        if (this.qryEntities == null) {
-            this.qryEntities = new ArrayList<>(qryEntities);
-
-            return this;
-        }
-
-        for (QueryEntity entity : qryEntities) {
-            boolean found = false;
+    public CacheConfiguration<K, V> setQueryEntities(@Nullable 
Collection<QueryEntity> qryEntities) {
+        
checkQueryEntityConfigurationSource(QueryEntityConfigurationSource.QUERY_ENTITIES);
 
-            for (QueryEntity existing : this.qryEntities) {
-                if (Objects.equals(entity.findValueType(), 
existing.findValueType())) {
-                    found = true;
+        Collection<QueryEntity> safeEntities = qryEntities == null ? 
Collections.emptyList() : qryEntities;
 
-                    break;
-                }
-            }
+        this.qryEntities = new ArrayList<>(safeEntities);
 
-            if (!found)
-                this.qryEntities.add(entity);
-        }
+        qryEntityCfgSrc = QueryEntityConfigurationSource.QUERY_ENTITIES;
 
         return this;
     }
 
     /**
-     * Clear query entities.
+     * Clears query entities.
+     * <p>
+     * Calling this method does not reset the API used to configure query 
entities and does not allow switching between
+     * {@link #setIndexedTypes} and {@link #setQueryEntities}.
      *
      * @return {@code this} for chaining.
      */
     public CacheConfiguration<K, V> clearQueryEntities() {
-        this.qryEntities = null;
+        qryEntities = null;
 
         return this;
     }
@@ -2484,6 +2496,29 @@ public class CacheConfiguration<K, V> extends 
MutableConfiguration<K, V> impleme
         return S.toString(CacheConfiguration.class, this);
     }
 
+    /** */
+    void replaceQueryEntities(Collection<QueryEntity> qryEntities) {
+        this.qryEntities = new ArrayList<>(qryEntities);
+    }
+
+    /** */
+    private void 
checkQueryEntityConfigurationSource(QueryEntityConfigurationSource src) {
+        if (qryEntityCfgSrc != null && qryEntityCfgSrc != src) {
+            String cacheName = name == null ? "<unnamed>" : name;
+
+            throw new 
CacheException(String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, 
cacheName));
+        }
+    }
+
+    /** API used to configure query entities. */
+    private enum QueryEntityConfigurationSource {
+        /** */
+        INDEXED_TYPES,
+
+        /** */
+        QUERY_ENTITIES
+    }
+
     /**
      *  Filter that accepts all nodes.
      */
diff --git 
a/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfigurationInternalAccessor.java
 
b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfigurationInternalAccessor.java
new file mode 100644
index 00000000000..edeafcae5e2
--- /dev/null
+++ 
b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfigurationInternalAccessor.java
@@ -0,0 +1,45 @@
+/*
+ * 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.ignite.configuration;
+
+import java.util.Collection;
+import org.apache.ignite.cache.QueryEntity;
+
+/**
+ * Provides internal access to {@link CacheConfiguration} implementation 
details.
+ * <p>
+ * This class is intended for internal use only and is not part of the 
supported public API.
+ */
+public final class CacheConfigurationInternalAccessor {
+    /** */
+    private CacheConfigurationInternalAccessor() {
+        // No-op.
+    }
+
+    /**
+     * Replaces query entities without checking whether {@link 
CacheConfiguration#setIndexedTypes} or
+     * {@link CacheConfiguration#setQueryEntities} was previously used.
+     * Preserves the query-entity configuration source.
+     *
+     * @param cfg Cache configuration.
+     * @param qryEntities Query entities.
+     */
+    public static void replaceQueryEntities(CacheConfiguration<?, ?> cfg, 
Collection<QueryEntity> qryEntities) {
+        cfg.replaceQueryEntities(qryEntities);
+    }
+}
diff --git 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/ClusterCachesInfo.java
 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/ClusterCachesInfo.java
index 9326dc68533..102248948e7 100644
--- 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/ClusterCachesInfo.java
+++ 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/ClusterCachesInfo.java
@@ -46,6 +46,7 @@ import org.apache.ignite.cache.CacheExistsException;
 import org.apache.ignite.cache.QueryEntity;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.CacheConfigurationInternalAccessor;
 import org.apache.ignite.configuration.DataRegionConfiguration;
 import org.apache.ignite.configuration.DataStorageConfiguration;
 import org.apache.ignite.configuration.NearCacheConfiguration;
@@ -1865,7 +1866,8 @@ public class ClusterCachesInfo {
      */
     private CacheConfiguration<?, ?> mergeConfigurations(CacheConfiguration<?, 
?> loc, CacheConfiguration<?, ?> received) {
         // Schema is supposed to get merged earlier.
-        loc.setQueryEntities(received.getQueryEntities());
+        CacheConfigurationInternalAccessor.replaceQueryEntities(loc, 
received.getQueryEntities());
+
         loc.setSqlSchema(received.getSqlSchema());
         loc.setSqlFunctionClasses(received.getSqlFunctionClasses());
         loc.setSqlEscapeAll(received.isSqlEscapeAll());
diff --git 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
index 80e2f3e03fe..c4729397972 100644
--- 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
+++ 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
@@ -57,6 +57,7 @@ import 
org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
 import org.apache.ignite.cache.store.CacheStoreSessionListener;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.CacheConfigurationInternalAccessor;
 import org.apache.ignite.configuration.DataRegionConfiguration;
 import org.apache.ignite.configuration.DataStorageConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
@@ -1594,8 +1595,12 @@ public class GridCacheUtils {
      * @param recoveryMode Value of {@link GridKernalContext#recoveryMode()}.
      * @throws IgniteCheckedException If configuration is not valid.
      */
-    public static void initializeConfigDefaults(IgniteLogger log, 
CacheConfiguration cfg,
-        CacheObjectContext cacheObjCtx, boolean recoveryMode) throws 
IgniteCheckedException {
+    public static void initializeConfigDefaults(
+        IgniteLogger log,
+        CacheConfiguration cfg,
+        CacheObjectContext cacheObjCtx,
+        boolean recoveryMode
+    ) throws IgniteCheckedException {
         if (cfg.getCacheMode() == null)
             cfg.setCacheMode(DFLT_CACHE_MODE);
 
@@ -1654,8 +1659,8 @@ public class GridCacheUtils {
         Collection<QueryEntity> entities = cfg.getQueryEntities();
 
         if (!F.isEmpty(entities)) {
-            cfg.clearQueryEntities().setQueryEntities(
-                QueryUtils.normalizeQueryEntities(recoveryMode, entities, 
cfg));
+            CacheConfigurationInternalAccessor.replaceQueryEntities(
+                cfg, QueryUtils.normalizeQueryEntities(recoveryMode, entities, 
cfg));
         }
     }
 
@@ -2072,8 +2077,11 @@ public class GridCacheUtils {
         boolean isSqlEscape,
         int qryParallelism
     ) {
-        return new CacheConfiguration<>(oldCfg)
-                .setQueryEntities(entities)
+        CacheConfiguration<K, V> newCfg = new CacheConfiguration<>(oldCfg);
+
+        CacheConfigurationInternalAccessor.replaceQueryEntities(newCfg, 
entities);
+
+        return newCfg
                 .setSqlSchema(sqlSchema)
                 .setSqlEscapeAll(isSqlEscape)
                 .setQueryParallelism(qryParallelism);
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheConfigurationQueryEntityTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheConfigurationQueryEntityTest.java
new file mode 100644
index 00000000000..92d227f7329
--- /dev/null
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheConfigurationQueryEntityTest.java
@@ -0,0 +1,716 @@
+/*
+ * 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.ignite.internal.processors.cache;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import javax.cache.CacheException;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.Ignition;
+import org.apache.ignite.cache.CacheKeyConfiguration;
+import org.apache.ignite.cache.QueryEntity;
+import org.apache.ignite.cache.QueryIndex;
+import org.apache.ignite.cache.affinity.AffinityKeyMapped;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
+import org.apache.ignite.cache.query.annotations.QuerySqlField;
+import org.apache.ignite.client.ClientCacheConfiguration;
+import org.apache.ignite.client.IgniteClient;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.ClientConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.processors.query.QueryEntityEx;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.junit.Test;
+
+import static org.apache.ignite.cluster.ClusterState.ACTIVE;
+import static 
org.apache.ignite.configuration.CacheConfiguration.MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE;
+import static org.apache.ignite.testframework.GridTestUtils.assertThrows;
+import static org.junit.Assert.assertArrayEquals;
+
+/** Tests query entity configuration in {@link CacheConfiguration}. */
+public class CacheConfigurationQueryEntityTest extends GridCommonAbstractTest {
+    /** */
+    private static final String CACHE_NAME = "query-entity-cache";
+
+    /** */
+    private static final String NAME_FIELD = "name";
+
+    /** */
+    private static final String AGE_FIELD = "age";
+
+    /** */
+    private boolean staticCfg;
+
+    /** */
+    private boolean indexedTypesCfg;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String 
igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        if (staticCfg) {
+            CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+            if (indexedTypesCfg)
+                ccfg.setIndexedTypes(Integer.class, Person.class);
+
+            cfg.setCacheConfiguration(ccfg);
+        }
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /**
+     * Verifies that a repeated {@link CacheConfiguration#setQueryEntities} 
call replaces query entities
+     * configured by the previous call.
+     */
+    @Test
+    public void testRepeatedSetQueryEntitiesReplacesPreviousEntities() throws 
Exception {
+        IgniteEx node = startGrid(0);
+
+        CacheConfiguration<Integer, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        QueryEntity first = new QueryEntity()
+            .setKeyType(Integer.class.getName())
+            .setValueType(Person.class.getName());
+
+        QueryEntity second = new QueryEntity()
+            .setKeyType(Integer.class.getName())
+            .setValueType(AnnotatedPerson.class.getName());
+
+        ccfg.setQueryEntities(Collections.singleton(first));
+        ccfg.setQueryEntities(Collections.singleton(second));
+
+        assertEquals(1, ccfg.getQueryEntities().size());
+        assertSame(second, ccfg.getQueryEntities().iterator().next());
+
+        node.createCache(ccfg);
+
+        QueryEntity entity = singleQueryEntity(node);
+
+        assertEquals(second.getKeyType(), entity.getKeyType());
+        assertEquals(second.getValueType(), entity.getValueType());
+    }
+
+    /**
+     * Verifies that a repeated {@link CacheConfiguration#setQueryEntities} 
call replaces the previously
+     * configured entity even when both entities have the same value type.
+     */
+    @Test
+    public void testRepeatedSetQueryEntitiesReplacesEntityWithSameValueType() 
throws Exception {
+        IgniteEx node = startGrid(0);
+
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        QueryEntity first = new QueryEntity()
+            .setKeyType(Integer.class.getName())
+            .setValueType(Person.class.getName());
+
+        QueryEntity second = new QueryEntity()
+            .setKeyType(String.class.getName())
+            .setValueType(Person.class.getName());
+
+        ccfg.setQueryEntities(Collections.singleton(first));
+        ccfg.setQueryEntities(Collections.singleton(second));
+
+        assertEquals(1, ccfg.getQueryEntities().size());
+
+        node.createCache(ccfg);
+
+        QueryEntity entity = singleQueryEntity(node);
+
+        assertEquals(second.getKeyType(), entity.getKeyType());
+        assertEquals(second.getValueType(), entity.getValueType());
+    }
+
+    /**
+     * Verifies that an empty/null {@link CacheConfiguration#setQueryEntities} 
call clears query entities configured
+     * by the previous call.
+     */
+    @Test
+    public void testEmptySetQueryEntitiesClearsPreviousEntities() {
+        for (Object entities : Arrays.asList(Collections.emptyList(), null)) {
+            CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+            
ccfg.setQueryEntities(Collections.singleton(configuredEntity(Person.class)));
+
+            assertEquals(1, ccfg.getQueryEntities().size());
+
+            ccfg.setQueryEntities((Collection<QueryEntity>)entities);
+
+            assertTrue(ccfg.getQueryEntities().isEmpty());
+        }
+    }
+
+    /**
+     * Verifies that repeated {@link CacheConfiguration#setIndexedTypes} calls 
replace indexed types
+     * and query entities while preserving previously configured affinity 
mappings.
+     */
+    @Test
+    public void 
testRepeatedSetIndexedTypesReplacesQueryEntitiesAndPreservesKeyConfiguration() 
throws Exception {
+        IgniteEx node = startGrid(0);
+
+        CacheConfiguration<Object, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        ccfg.setIndexedTypes(FirstKey.class, Person.class);
+        ccfg.setIndexedTypes(SecondKey.class, AnnotatedPerson.class);
+
+        assertArrayEquals(
+            new Class<?>[] {SecondKey.class, AnnotatedPerson.class},
+            ccfg.getIndexedTypes()
+        );
+
+        node.createCache(ccfg);
+
+        QueryEntity entity = singleQueryEntity(node);
+
+        assertEquals(SecondKey.class.getName(), entity.getKeyType());
+        assertEquals(AnnotatedPerson.class.getName(), entity.getValueType());
+
+        CacheKeyConfiguration[] keyCfg = ccfg.getKeyConfiguration();
+
+        assertNotNull(keyCfg);
+        assertEquals(2, keyCfg.length);
+
+        assertEquals(FirstKey.class.getName(), keyCfg[0].getTypeName());
+        assertEquals("firstAffinityKey", keyCfg[0].getAffinityKeyFieldName());
+
+        assertEquals(SecondKey.class.getName(), keyCfg[1].getTypeName());
+        assertEquals("secondAffinityKey", keyCfg[1].getAffinityKeyFieldName());
+    }
+
+    /** Verifies that empty and null indexed types clear SQL configuration 
without removing existing affinity mappings. */
+    @Test
+    public void 
testEmptySetIndexedTypesClearsQueryEntitiesAndPreservesKeyConfiguration() {
+        for (Class<?>[] indexedTypes : new Class<?>[][] {new Class<?>[0], 
null}) {
+            CacheConfiguration<Object, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+            ccfg.setIndexedTypes(FirstKey.class, Person.class);
+
+            assertEquals(2, ccfg.getIndexedTypes().length);
+            assertEquals(1, ccfg.getQueryEntities().size());
+
+            CacheKeyConfiguration[] keyCfg = ccfg.getKeyConfiguration();
+
+            assertNotNull(keyCfg);
+            assertEquals(1, keyCfg.length);
+
+            ccfg.setIndexedTypes(indexedTypes);
+
+            assertArrayEquals(new Class<?>[0], ccfg.getIndexedTypes());
+            assertTrue(ccfg.getQueryEntities().isEmpty());
+            assertSame(keyCfg, ccfg.getKeyConfiguration());
+        }
+    }
+
+    /**
+     * Verifies that repeated indexed-types configuration with the same key 
type replaces the previous affinity mapping
+     * without creating duplicates.
+     */
+    @Test
+    public void 
testRepeatedSetIndexedTypesReplacesAffinityMappingForSameKeyType() {
+        CacheConfiguration<Object, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        ccfg.setIndexedTypes(FirstKey.class, Person.class);
+
+        CacheKeyConfiguration first = ccfg.getKeyConfiguration()[0];
+
+        ccfg.setIndexedTypes(FirstKey.class, AnnotatedPerson.class);
+
+        CacheKeyConfiguration[] keyCfg = ccfg.getKeyConfiguration();
+
+        assertNotNull(keyCfg);
+        assertEquals(1, keyCfg.length);
+        assertNotSame(first, keyCfg[0]);
+        assertEquals(FirstKey.class.getName(), keyCfg[0].getTypeName());
+        assertEquals("firstAffinityKey", keyCfg[0].getAffinityKeyFieldName());
+    }
+
+    /** Verifies that indexed types add affinity mappings without removing 
explicit key configuration. */
+    @Test
+    public void testSetIndexedTypesPreservesExplicitKeyConfiguration() {
+        CacheConfiguration<Object, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        CacheKeyConfiguration explicit = new 
CacheKeyConfiguration("ExplicitKey", "explicitAffinityKey");
+
+        ccfg.setKeyConfiguration(explicit);
+
+        ccfg.setIndexedTypes(SecondKey.class, Person.class);
+
+        CacheKeyConfiguration[] keyCfg = ccfg.getKeyConfiguration();
+        assertNotNull(keyCfg);
+
+        assertEquals(2, keyCfg.length);
+
+        assertSame(explicit, keyCfg[0]);
+
+        assertEquals(SecondKey.class.getName(), keyCfg[1].getTypeName());
+        assertEquals("secondAffinityKey", keyCfg[1].getAffinityKeyFieldName());
+    }
+
+    /** Verifies that an annotation-derived affinity mapping replaces an 
existing mapping for the same type. */
+    @Test
+    public void 
testSetIndexedTypesReplacesExistingKeyConfigurationForSameType() {
+        CacheConfiguration<Object, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        CacheKeyConfiguration explicit =
+            new CacheKeyConfiguration(SecondKey.class.getName(), 
"explicitAffinityKey");
+
+        ccfg.setKeyConfiguration(explicit);
+
+        ccfg.setIndexedTypes(SecondKey.class, Person.class);
+
+        CacheKeyConfiguration[] keyCfg = ccfg.getKeyConfiguration();
+        assertNotNull(keyCfg);
+
+        assertEquals(1, keyCfg.length);
+
+        assertEquals(SecondKey.class.getName(), keyCfg[0].getTypeName());
+        assertEquals("secondAffinityKey", keyCfg[0].getAffinityKeyFieldName());
+    }
+
+    /**
+     * Verifies that query entities cannot be configured through {@link 
CacheConfiguration#setQueryEntities}
+     * after {@link CacheConfiguration#setIndexedTypes} was used.
+     */
+    @Test
+    public void testSetQueryEntitiesAfterSetIndexedTypesFails() {
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            .setIndexedTypes(Integer.class, Person.class);
+
+        assertThrows(
+            log,
+            () -> 
ccfg.setQueryEntities(Collections.singleton(configuredEntity(AnnotatedPerson.class))),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /**
+     * Verifies that query entities cannot be configured through {@link 
CacheConfiguration#setIndexedTypes}
+     * after {@link CacheConfiguration#setQueryEntities} was used.
+     */
+    @Test
+    public void testSetIndexedTypesAfterSetQueryEntitiesFails() {
+        LinkedHashMap<String, Boolean> idxFields = new LinkedHashMap<>();
+        idxFields.put(NAME_FIELD, true);
+        idxFields.put(AGE_FIELD, true);
+
+        QueryIndex idx = new 
QueryIndex().setName("PERSON_NAME_AGE_IDX").setFields(idxFields);
+
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            
.setQueryEntities(Collections.singleton(configuredEntity(AnnotatedPerson.class, 
idx)));
+
+        assertThrows(
+            log,
+            () -> ccfg.setIndexedTypes(Integer.class, AnnotatedPerson.class),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /**
+     * Verifies that clearing query entities does not allow switching from 
{@link CacheConfiguration#setIndexedTypes}
+     * to {@link CacheConfiguration#setQueryEntities}.
+     */
+    @Test
+    public void testClearQueryEntitiesDoesNotAllowSwitchFromIndexedTypes() {
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            .setIndexedTypes(Integer.class, Person.class);
+
+        ccfg.clearQueryEntities();
+
+        assertThrows(
+            log,
+            () -> 
ccfg.setQueryEntities(Collections.singleton(configuredEntity(Person.class))),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /**
+     * Verifies that clearing query entities does not allow switching from 
{@link CacheConfiguration#setQueryEntities}
+     * to {@link CacheConfiguration#setIndexedTypes}.
+     */
+    @Test
+    public void testClearQueryEntitiesDoesNotAllowSwitchFromQueryEntities() {
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            
.setQueryEntities(Collections.singleton(configuredEntity(Person.class)));
+
+        ccfg.clearQueryEntities();
+
+        assertThrows(
+            log,
+            () -> ccfg.setIndexedTypes(Integer.class, Person.class),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /** Verifies that empty or null indexed types cannot be configured after 
explicit query entities. */
+    @Test
+    public void testEmptySetIndexedTypesAfterSetQueryEntitiesFails() {
+        for (Class<?>[] indexedTypes : new Class<?>[][] {new Class<?>[0], 
null}) {
+            CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+                
.setQueryEntities(Collections.singleton(configuredEntity(Person.class)));
+
+            assertThrows(
+                log,
+                () -> ccfg.setIndexedTypes(indexedTypes),
+                CacheException.class,
+                String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, 
CACHE_NAME)
+            );
+        }
+    }
+
+    /** Verifies that configuring empty or null indexed types prevents 
switching to explicit query entities. */
+    @Test
+    public void testSetQueryEntitiesAfterEmptySetIndexedTypesFails() {
+        for (Class<?>[] indexedTypes : new Class<?>[][] {new Class<?>[0], 
null}) {
+            CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+                .setIndexedTypes(indexedTypes);
+
+            assertThrows(
+                log,
+                () -> 
ccfg.setQueryEntities(Collections.singleton(configuredEntity(Person.class))),
+                CacheException.class,
+                String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, 
CACHE_NAME)
+            );
+        }
+    }
+
+    /** Verifies that an empty query entities collection cannot be configured 
after indexed types. */
+    @Test
+    public void testEmptySetQueryEntitiesAfterSetIndexedTypesFails() {
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            .setIndexedTypes(Integer.class, Person.class);
+
+        assertThrows(
+            log,
+            () -> ccfg.setQueryEntities(Collections.emptyList()),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /** Verifies that configuring an empty query entities collection prevents 
switching to indexed types. */
+    @Test
+    public void testSetIndexedTypesAfterEmptySetQueryEntitiesFails() {
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            .setQueryEntities(Collections.emptyList());
+
+        assertThrows(
+            log,
+            () -> ccfg.setIndexedTypes(Integer.class, Person.class),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /** Verifies that clearing query entities does not prevent configuring 
them again through the same API. */
+    @Test
+    public void testSetQueryEntitiesCanBeUsedAfterClearQueryEntities() {
+        CacheConfiguration<Integer, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        QueryEntity first = configuredEntity(Person.class);
+        QueryEntity second = configuredEntity(AnnotatedPerson.class);
+
+        ccfg.setQueryEntities(Collections.singleton(first));
+
+        ccfg.clearQueryEntities();
+
+        ccfg.setQueryEntities(Collections.singleton(second));
+
+        Collection<QueryEntity> entities = ccfg.getQueryEntities();
+
+        assertEquals(1, entities.size());
+        assertSame(second, entities.iterator().next());
+    }
+
+    /** Verifies that clearing query entities does not prevent configuring 
indexed types again through the same API. */
+    @Test
+    public void testSetIndexedTypesCanBeUsedAfterClearQueryEntities() {
+        CacheConfiguration<Object, Object> ccfg = new 
CacheConfiguration<>(CACHE_NAME);
+
+        ccfg.setIndexedTypes(FirstKey.class, Person.class);
+
+        ccfg.clearQueryEntities();
+
+        ccfg.setIndexedTypes(SecondKey.class, AnnotatedPerson.class);
+
+        Collection<QueryEntity> entities = ccfg.getQueryEntities();
+
+        assertEquals(1, entities.size());
+
+        QueryEntity entity = entities.iterator().next();
+
+        assertEquals(SecondKey.class.getName(), entity.getKeyType());
+        assertEquals(AnnotatedPerson.class.getName(), entity.getValueType());
+    }
+
+    /** Verifies that the indexed-types configuration source is preserved when 
{@link CacheConfiguration} is copied. */
+    @Test
+    public void testIndexedTypesConfigurationSourceIsPreservedOnCopy() {
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            .setIndexedTypes(Integer.class, Person.class);
+
+        CacheConfiguration<Integer, Person> copy = new 
CacheConfiguration<>(ccfg);
+
+        assertThrows(
+            log,
+            () -> 
copy.setQueryEntities(Collections.singleton(configuredEntity(Person.class))),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /** Verifies that the query-entities configuration source is preserved 
when {@link CacheConfiguration} is copied. */
+    @Test
+    public void testQueryEntitiesConfigurationSourceIsPreservedOnCopy() {
+        CacheConfiguration<Integer, Person> ccfg = new 
CacheConfiguration<Integer, Person>(CACHE_NAME)
+            
.setQueryEntities(Collections.singleton(configuredEntity(Person.class)));
+
+        CacheConfiguration<Integer, Person> copy = new 
CacheConfiguration<>(ccfg);
+
+        assertThrows(
+            log,
+            () -> copy.setIndexedTypes(Integer.class, Person.class),
+            CacheException.class,
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, CACHE_NAME)
+        );
+    }
+
+    /**
+     * Verifies that a statically configured cache using {@link 
CacheConfiguration#setIndexedTypes} starts successfully
+     * and preserves its query-entity configuration source during cache 
initialization.
+     */
+    @Test
+    public void testCacheConfiguredWithIndexedTypesStartsSuccessfully() throws 
Exception {
+        staticCfg = true;
+        indexedTypesCfg = true;
+
+        IgniteEx node = startGrid(0);
+
+        assertNotNull(node.cache(CACHE_NAME));
+
+        QueryEntity entity = singleQueryEntity(node);
+
+        assertEquals(Integer.class.getName(), entity.getKeyType());
+        assertEquals(Person.class.getName(), entity.getValueType());
+    }
+
+    /**
+     * Verifies that a node with a statically configured cache using {@link 
CacheConfiguration#setIndexedTypes} can
+     * join an active cluster.
+     */
+    @Test
+    public void testNodeWithIndexedTypesConfigurationJoinsCluster() throws 
Exception {
+        staticCfg = true;
+        indexedTypesCfg = true;
+
+        IgniteEx node0 = startGrid(0);
+
+        node0.cluster().state(ACTIVE);
+
+        IgniteEx node1 = startGrid(1);
+
+        assertNotNull(node1.cache(CACHE_NAME));
+
+        QueryEntity entity = singleQueryEntity(node1);
+
+        assertEquals(Integer.class.getName(), entity.getKeyType());
+        assertEquals(Person.class.getName(), entity.getValueType());
+    }
+
+    /**
+     * Verifies that adding SQL metadata to a statically configured cache 
preserves {@link QueryEntityEx} and its
+     * extended metadata.
+     *
+     * <p>A schema-add operation patches both the runtime cache configuration 
and the cache descriptor configuration.
+     * Internal query-entity replacement must keep these configurations 
independent and must not modify the descriptor
+     * configuration through a shared mutable collection.</p>
+     */
+    @Test
+    public void testSchemaAddPreservesQueryEntityExMetadata() throws Exception 
{
+        staticCfg = true;
+
+        IgniteEx node = startGrid(0);
+
+        DynamicCacheDescriptor desc = 
node.context().cache().cacheDescriptor(CACHE_NAME);
+
+        assertTrue(desc.cacheConfiguration().getQueryEntities().isEmpty());
+
+        node.cache(CACHE_NAME).query(new SqlFieldsQuery(
+            "CREATE TABLE TEST_TBL (ID1 INT, ID2 INT, VAL VARCHAR NOT NULL, 
PRIMARY KEY (ID1, ID2)" +
+                ") WITH \"CACHE_NAME=" + CACHE_NAME + "\""
+        )).getAll();
+
+        QueryEntity entity = singleQueryEntity(node);
+
+        assertEquals("TEST_TBL", entity.getTableName());
+
+        assertTrue(entity instanceof QueryEntityEx);
+
+        QueryEntityEx entityEx = (QueryEntityEx)entity;
+
+        assertTrue(entityEx.sql());
+        assertTrue(entityEx.isPreserveKeysOrder());
+        assertTrue(entityEx.fillAbsentPKsWithDefaults());
+    }
+
+    /** Verifies that CREATE TABLE configures query entities for a new cache. 
*/
+    @Test
+    public void testCreateTableConfiguresQueryEntities() throws Exception {
+        IgniteEx node = startGrid(0);
+
+        IgniteCache<Integer, Person> dfltCache = 
node.getOrCreateCache(DEFAULT_CACHE_NAME);
+
+        assertNull(node.context().cache().cacheDescriptor(CACHE_NAME));
+
+        dfltCache.query(new SqlFieldsQuery(
+            "CREATE TABLE TEST_TBL (ID1 INT, ID2 INT, VAL VARCHAR NOT NULL, 
PRIMARY KEY (ID1, ID2)" +
+                ") WITH \"CACHE_NAME=" + CACHE_NAME + "\""
+        )).getAll();
+
+        QueryEntity entity = singleQueryEntity(node);
+
+        assertEquals("TEST_TBL", entity.getTableName());
+
+        assertTrue(entity instanceof QueryEntityEx);
+
+        QueryEntityEx entityEx = (QueryEntityEx)entity;
+
+        assertTrue(entityEx.sql());
+        assertTrue(entityEx.isPreserveKeysOrder());
+        assertTrue(entityEx.fillAbsentPKsWithDefaults());
+    }
+
+    /** Verifies that query entities supplied by a thin client are correctly 
read and applied when creating a cache. */
+    @Test
+    public void testCreateCacheWithQueryEntitiesThroughThinClient() throws 
Exception {
+        IgniteEx node = startGrid(0);
+
+        QueryEntity entity = configuredEntity(Person.class);
+
+        ClientCacheConfiguration ccfg = new ClientCacheConfiguration()
+            .setName(CACHE_NAME)
+            .setQueryEntities(entity);
+
+        try (IgniteClient client = Ignition.startClient(
+            new ClientConfiguration().setAddresses("127.0.0.1:10800")
+        )) {
+            client.createCache(ccfg);
+
+            assertNotNull(node.cache(CACHE_NAME));
+
+            QueryEntity actual = singleQueryEntity(node);
+
+            assertEquals(entity.getKeyType(), actual.getKeyType());
+            assertEquals(entity.getValueType(), actual.getValueType());
+            assertEquals(entity.getFields(), actual.getFields());
+        }
+    }
+
+    /** */
+    private static QueryEntity configuredEntity(Class<?> valCls, QueryIndex... 
indexes) {
+        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
+
+        fields.put(NAME_FIELD, String.class.getName());
+        fields.put(AGE_FIELD, Integer.class.getName());
+
+        QueryEntity res = new QueryEntity()
+            .setKeyType(Integer.class.getName())
+            .setValueType(valCls.getName())
+            .setTableName(valCls.getSimpleName())
+            .setFields(fields);
+
+        if (indexes.length != 0)
+            res.setIndexes(Arrays.asList(indexes));
+
+        return res;
+    }
+
+    /** */
+    private static QueryEntity singleQueryEntity(IgniteEx node) {
+        Collection<QueryEntity> entities = 
(Collection<QueryEntity>)node.context().cache()
+            .cacheConfiguration(CACHE_NAME)
+            .getQueryEntities();
+
+        assertEquals(1, entities.size());
+
+        return entities.iterator().next();
+    }
+
+    /** */
+    private static class Person {
+        /** */
+        private final String name;
+
+        /** */
+        private final int age;
+
+        /** */
+        private Person(String name, int age) {
+            this.name = name;
+            this.age = age;
+        }
+    }
+
+    /** */
+    private static class AnnotatedPerson {
+        /** */
+        @QuerySqlField(index = true, notNull = true)
+        private String name;
+
+        /** */
+        @QuerySqlField
+        private int age;
+
+        /** */
+        @QuerySqlField
+        private float weight;
+
+        /** */
+        @QuerySqlField(scale = 2)
+        private float height;
+    }
+
+    /** */
+    private static class FirstKey {
+        /** */
+        @AffinityKeyMapped
+        private int firstAffinityKey;
+    }
+
+    /** */
+    private static class SecondKey {
+        /** */
+        @AffinityKeyMapped
+        private int secondAffinityKey;
+    }
+}
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractInsertSqlQuerySelfTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractInsertSqlQuerySelfTest.java
index 5a249c57248..229820e34cd 100644
--- 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractInsertSqlQuerySelfTest.java
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractInsertSqlQuerySelfTest.java
@@ -246,8 +246,10 @@ public abstract class 
IgniteCacheAbstractInsertSqlQuerySelfTest extends GridComm
             .setCacheMode(partitioned ? CacheMode.PARTITIONED : 
CacheMode.REPLICATED)
             .setAtomicityMode(CacheAtomicityMode.ATOMIC)
             .setBackups(1)
-            .setSqlEscapeAll(escapeSql)
-            .setIndexedTypes(idxTypes);
+            .setSqlEscapeAll(escapeSql);
+
+        if (idxTypes.length > 0)
+            res.setIndexedTypes(idxTypes);
 
         for (int i = 0; i < idxTypes.length / 2; i++) {
             Class<?> keyType = idxTypes[i];
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractQuerySelfTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractQuerySelfTest.java
index fe6a67abf32..dc51a3c1a1f 100644
--- 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractQuerySelfTest.java
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAbstractQuerySelfTest.java
@@ -32,6 +32,7 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.Callable;
@@ -247,9 +248,45 @@ public abstract class IgniteCacheAbstractQuerySelfTest 
extends GridCommonAbstrac
      * @return cache instance
      */
     protected <K, V> IgniteCache<K, V> jcache(Ignite ig, Class<K> clsK, 
Class<V> clsV) {
-        IgniteCache<K, V> cache = jcache(ig, cacheConfiguration(), clsK, clsV);
+        return jcache(ig, cacheConfiguration(), clsK, clsV);
+    }
 
-        return cache;
+    /** {@inheritDoc} */
+    @Override protected <K, V> IgniteCache<K, V> jcache(
+        Ignite ig,
+        CacheConfiguration cfg,
+        Class<K> clsK,
+        Class<V> clsV
+    ) {
+        return jcacheWithSpecifiedName(ig, cfg, clsK, clsV, 
clsK.getSimpleName() + "-" + clsV.getSimpleName());
+    }
+
+    /** */
+    private <K, V> IgniteCache<K, V> jcacheWithSpecifiedName(
+        Ignite ig,
+        CacheConfiguration cfg,
+        Class<K> clsK,
+        Class<V> clsV,
+        String cacheName
+    ) {
+        CacheConfiguration<K, V> ccfg = new CacheConfiguration<>(cfg);
+
+        List<QueryEntity> entities = new ArrayList<>(ccfg.getQueryEntities());
+
+        QueryEntity entity = new QueryEntity(clsK, clsV);
+
+        boolean configured = entities.stream().anyMatch(
+            existing -> Objects.equals(existing.getValueType(), 
entity.getValueType())
+        );
+
+        if (!configured)
+            entities.add(entity);
+
+        ccfg.setQueryEntities(entities);
+
+        ccfg.setName(cacheName);
+
+        return ig.getOrCreateCache(ccfg);
     }
 
     /**
@@ -630,11 +667,7 @@ public abstract class IgniteCacheAbstractQuerySelfTest 
extends GridCommonAbstrac
     @Test
     public void testSimpleCustomTableName() {
         CacheConfiguration<Integer, Object> cacheConf = new 
CacheConfiguration<Integer, Object>(cacheConfiguration())
-            .setName(DEFAULT_CACHE_NAME)
-            .setQueryEntities(Arrays.asList(
-                new QueryEntity(Integer.class, Type1.class),
-                new QueryEntity(Integer.class, Type2.class)
-            ));
+            .setName(DEFAULT_CACHE_NAME);
 
         final IgniteCache<Integer, Object> cache = 
ignite().getOrCreateCache(cacheConf);
 
@@ -1186,7 +1219,7 @@ public abstract class IgniteCacheAbstractQuerySelfTest 
extends GridCommonAbstrac
             new QueryEntity(String.class, ObjectValueOther.class)
         ));
 
-        IgniteCache<Object, Object> c = jcache(ignite(), conf, Object.class, 
Object.class);
+        IgniteCache<Object, Object> c = jcache(ignite(), conf, 
"Object-Object");
 
         c.put(1, new ObjectValue("ObjectValue str", 1));
         c.put("key", new ObjectValueOther("ObjectValueOther str"));
@@ -1232,7 +1265,9 @@ public abstract class IgniteCacheAbstractQuerySelfTest 
extends GridCommonAbstrac
      */
     @Test
     public void testPaginationIteratorDefaultCache() throws Exception {
-        testPaginationIterator(jcache(ignite(), cacheConfiguration(), 
DEFAULT_CACHE_NAME, Integer.class, Integer.class));
+        CacheConfiguration<Integer, Integer> ccfg = cacheConfiguration();
+
+        testPaginationIterator(jcacheWithSpecifiedName(ignite(), ccfg, 
Integer.class, Integer.class, DEFAULT_CACHE_NAME));
     }
 
     /**
@@ -1240,7 +1275,7 @@ public abstract class IgniteCacheAbstractQuerySelfTest 
extends GridCommonAbstrac
      */
     @Test
     public void testPaginationIteratorNamedCache() throws Exception {
-        testPaginationIterator(jcache(ignite(), cacheConfiguration(), 
Integer.class, Integer.class));
+        testPaginationIterator(jcache(ignite(), Integer.class, Integer.class));
     }
 
     /**
@@ -1274,7 +1309,9 @@ public abstract class IgniteCacheAbstractQuerySelfTest 
extends GridCommonAbstrac
      */
     @Test
     public void testPaginationGetDefaultCache() throws Exception {
-        testPaginationGet(jcache(ignite(), cacheConfiguration(), 
DEFAULT_CACHE_NAME, Integer.class, Integer.class));
+        CacheConfiguration<Integer, Integer> ccfg = cacheConfiguration();
+
+        testPaginationGet(jcacheWithSpecifiedName(ignite(), ccfg, 
Integer.class, Integer.class, DEFAULT_CACHE_NAME));
     }
 
     /**
@@ -1282,7 +1319,7 @@ public abstract class IgniteCacheAbstractQuerySelfTest 
extends GridCommonAbstrac
      */
     @Test
     public void testPaginationGetNamedCache() throws Exception {
-        testPaginationGet(jcache(ignite(), cacheConfiguration(), 
Integer.class, Integer.class));
+        testPaginationGet(jcache(ignite(), Integer.class, Integer.class));
     }
 
     /**
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheDuplicateEntityConfigurationSelfTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheDuplicateEntityConfigurationSelfTest.java
deleted file mode 100644
index d9ef6627baa..00000000000
--- 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheDuplicateEntityConfigurationSelfTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.ignite.internal.processors.cache;
-
-import java.util.Arrays;
-import java.util.LinkedHashMap;
-import org.apache.ignite.cache.QueryEntity;
-import org.apache.ignite.cache.query.annotations.QuerySqlField;
-import org.apache.ignite.configuration.CacheConfiguration;
-import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
-import org.junit.Test;
-
-/**
- *
- */
-public class IgniteCacheDuplicateEntityConfigurationSelfTest extends 
GridCommonAbstractTest {
-    /** {@inheritDoc} */
-    @Override protected void beforeTestsStarted() throws Exception {
-        startGrid(0);
-    }
-
-    /**
-     * @throws Exception If failed.
-     */
-    @Test
-    public void testClassDuplicatesQueryEntity() throws Exception {
-        String cacheName = "duplicate";
-
-        CacheConfiguration ccfg = new CacheConfiguration(cacheName);
-
-        ccfg.setIndexedTypes(Integer.class, Person.class);
-
-        QueryEntity entity = new QueryEntity();
-
-        entity.setKeyType(Integer.class.getName());
-        entity.setValueType(Person.class.getName());
-
-        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
-
-        fields.put("name", String.class.getName());
-
-        entity.setFields(fields);
-
-        ccfg.setQueryEntities(Arrays.asList(entity));
-
-        try {
-            ignite(0).getOrCreateCache(ccfg);
-        }
-        finally {
-            ignite(0).destroyCache(cacheName);
-        }
-    }
-
-    /**
-     * @throws Exception If failed.
-     */
-    @Test
-    public void testClassDuplicatesQueryReverse() throws Exception {
-        String cacheName = "duplicate";
-
-        CacheConfiguration ccfg = new CacheConfiguration(cacheName);
-
-        QueryEntity entity = new QueryEntity();
-
-        entity.setKeyType(Integer.class.getName());
-        entity.setValueType(Person.class.getName());
-
-        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
-
-        fields.put("name", String.class.getName());
-
-        entity.setFields(fields);
-
-        ccfg.setQueryEntities(Arrays.asList(entity));
-
-        ccfg.setIndexedTypes(Integer.class, Person.class);
-
-        try {
-            ignite(0).getOrCreateCache(ccfg);
-        }
-        finally {
-            ignite(0).destroyCache(cacheName);
-        }
-    }
-
-    /** */
-    private static class Person {
-        /** */
-        @QuerySqlField
-        private String name;
-    }
-}
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
index 000f1806381..739bffc9724 100644
--- 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
@@ -81,8 +81,7 @@ public class IgniteQueryDedicatedPoolTest extends 
GridCommonAbstractTest {
 
         CacheConfiguration<Integer, Integer> ccfg = new 
CacheConfiguration<>(DEFAULT_CACHE_NAME);
 
-        ccfg.setIndexedTypes(Integer.class, Integer.class);
-        ccfg.setIndexedTypes(Byte.class, Byte.class);
+        ccfg.setIndexedTypes(Integer.class, Integer.class, Byte.class, 
Byte.class);
         ccfg.setSqlFunctionClasses(IgniteQueryDedicatedPoolTest.class);
         ccfg.setName(CACHE_NAME);
 
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/RunningQueriesTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/RunningQueriesTest.java
index 9100505883a..d75d2091a1e 100644
--- 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/RunningQueriesTest.java
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/RunningQueriesTest.java
@@ -138,7 +138,6 @@ public class RunningQueriesTest extends 
AbstractIndexingCommonTest {
         IgniteCache<Integer, Integer> cache = ignite.getOrCreateCache(new 
CacheConfiguration<Integer, Integer>()
             .setName(DEFAULT_CACHE_NAME)
             .setQueryEntities(Collections.singletonList(new 
QueryEntity(Integer.class, Integer.class)))
-            .setIndexedTypes(Integer.class, Integer.class)
         );
 
         cache.put(100000, 0);
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/BaseH2CompareQueryTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/BaseH2CompareQueryTest.java
index 872a170e5c2..e75ef5dd835 100644
--- 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/BaseH2CompareQueryTest.java
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/BaseH2CompareQueryTest.java
@@ -117,13 +117,7 @@ public class BaseH2CompareQueryTest extends 
AbstractH2CompareQueryTest {
 
     /** {@inheritDoc} */
     @Override protected void createCaches() {
-        cacheOrg = jcache(
-            ignite,
-            cacheConfiguration(ORG, CacheMode.PARTITIONED, Integer.class, 
Organization.class),
-            ORG,
-            Integer.class,
-            Organization.class
-        );
+        cacheOrg = ignite.cache(ORG);
         cachePers = ignite.cache(PERS);
         cachePurch = ignite.cache(PURCH);
         cacheProd = ignite.cache(PROD);
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/twostep/NoneOrSinglePartitionsQueryOptimizationsTest.java
 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/twostep/NoneOrSinglePartitionsQueryOptimizationsTest.java
index 754f132fbb6..07a52c1c1ea 100644
--- 
a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/twostep/NoneOrSinglePartitionsQueryOptimizationsTest.java
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/twostep/NoneOrSinglePartitionsQueryOptimizationsTest.java
@@ -91,7 +91,7 @@ public class NoneOrSinglePartitionsQueryOptimizationsTest 
extends GridCommonAbst
         QueryEntity entity = new QueryEntity(Integer.class, 
JoinSqlTestHelper.Organization.class);
 
         entity.setKeyFieldName("ID");
-        entity.getFields().put("ID", String.class.getName());
+        entity.getFields().put("ID", Integer.class.getName());
 
         return Collections.singletonList(entity);
     }
@@ -102,9 +102,6 @@ public class NoneOrSinglePartitionsQueryOptimizationsTest 
extends GridCommonAbst
     private static Collection<QueryEntity> personQueryEntity() {
         QueryEntity entity = new QueryEntity(Integer.class, 
JoinSqlTestHelper.Person.class);
 
-        entity.setKeyFieldName("ID");
-        entity.getFields().put("ID", String.class.getName());
-
         return Collections.singletonList(entity);
     }
 
@@ -123,7 +120,6 @@ public class NoneOrSinglePartitionsQueryOptimizationsTest 
extends GridCommonAbst
             new CacheConfiguration<Integer, 
JoinSqlTestHelper.Person>(PERS_CACHE_NAME)
                 .setCacheMode(CacheMode.PARTITIONED)
                 .setSqlSchema(PERS_CACHE_NAME)
-                .setIndexedTypes(Integer.class, JoinSqlTestHelper.Person.class)
                 .setQueryEntities(personQueryEntity())
         );
 
diff --git 
a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite6.java
 
b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite6.java
index 3618b32d6c3..4029a6d716a 100644
--- 
a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite6.java
+++ 
b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite6.java
@@ -18,13 +18,13 @@
 package org.apache.ignite.testsuites;
 
 import org.apache.ignite.internal.processors.cache.AffinityAliasKeyTest;
+import 
org.apache.ignite.internal.processors.cache.CacheConfigurationQueryEntityTest;
 import 
org.apache.ignite.internal.processors.cache.CacheOffheapBatchIndexingMultiTypeTest;
 import 
org.apache.ignite.internal.processors.cache.GridCacheQueryIndexDisabledSelfTest;
 import 
org.apache.ignite.internal.processors.cache.GridCacheQueryInternalKeysSelfTest;
 import 
org.apache.ignite.internal.processors.cache.GridCacheQueryPartitionsReleaseTest;
 import 
org.apache.ignite.internal.processors.cache.IgniteBinaryObjectFieldsQuerySelfTest;
 import 
org.apache.ignite.internal.processors.cache.IgniteCacheDeleteSqlQuerySelfTest;
-import 
org.apache.ignite.internal.processors.cache.IgniteCacheDuplicateEntityConfigurationSelfTest;
 import 
org.apache.ignite.internal.processors.cache.IgniteCacheJoinPartitionedAndReplicatedCollocationTest;
 import 
org.apache.ignite.internal.processors.cache.IgniteCacheJoinQueryWithAffinityKeyTest;
 import 
org.apache.ignite.internal.processors.cache.IgniteCacheOffheapEvictQueryTest;
@@ -119,7 +119,7 @@ import org.junit.runners.Suite;
     IgniteCacheSqlQueryErrorSelfTest.class,
     IgniteCacheSqlDmlErrorSelfTest.class,
     SqlUnsupportedSelfTest.class,
-    IgniteCacheDuplicateEntityConfigurationSelfTest.class,
+    CacheConfigurationQueryEntityTest.class,
     IncorrectQueryEntityTest.class,
     IgniteDynamicSqlRestoreTest.class,
     IgniteSqlSplitterSelfTest.class,
diff --git 
a/modules/spring/src/test/config/query-entities/indexed-types-then-query-entities.xml
 
b/modules/spring/src/test/config/query-entities/indexed-types-then-query-entities.xml
new file mode 100644
index 00000000000..f368eabccb6
--- /dev/null
+++ 
b/modules/spring/src/test/config/query-entities/indexed-types-then-query-entities.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  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.
+-->
+
+<beans xmlns="http://www.springframework.org/schema/beans";
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+       xsi:schemaLocation="
+           http://www.springframework.org/schema/beans
+           http://www.springframework.org/schema/beans/spring-beans.xsd";>
+
+    <bean id="cacheConfiguration"
+          class="org.apache.ignite.configuration.CacheConfiguration">
+        <property name="name" value="query-entity-xml-cache"/>
+
+        <property name="indexedTypes">
+            <list>
+                <value>java.lang.Integer</value>
+                <value>java.lang.String</value>
+            </list>
+        </property>
+
+        <property name="queryEntities">
+            <list>
+                <bean class="org.apache.ignite.cache.QueryEntity">
+                    <property name="keyType" value="java.lang.Integer"/>
+                    <property name="valueType" value="java.lang.String"/>
+                </bean>
+            </list>
+        </property>
+    </bean>
+</beans>
\ No newline at end of file
diff --git 
a/modules/spring/src/test/config/query-entities/query-entities-then-indexed-types.xml
 
b/modules/spring/src/test/config/query-entities/query-entities-then-indexed-types.xml
new file mode 100644
index 00000000000..f03d9f735ac
--- /dev/null
+++ 
b/modules/spring/src/test/config/query-entities/query-entities-then-indexed-types.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  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.
+-->
+
+<beans xmlns="http://www.springframework.org/schema/beans";
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+       xsi:schemaLocation="
+           http://www.springframework.org/schema/beans
+           http://www.springframework.org/schema/beans/spring-beans.xsd";>
+
+    <bean id="cacheConfiguration"
+          class="org.apache.ignite.configuration.CacheConfiguration">
+        <property name="name" value="query-entity-xml-cache"/>
+
+        <property name="queryEntities">
+            <list>
+                <bean class="org.apache.ignite.cache.QueryEntity">
+                    <property name="keyType" value="java.lang.Integer"/>
+                    <property name="valueType" value="java.lang.String"/>
+                </bean>
+            </list>
+        </property>
+
+        <property name="indexedTypes">
+            <list>
+                <value>java.lang.Integer</value>
+                <value>java.lang.String</value>
+            </list>
+        </property>
+    </bean>
+</beans>
\ No newline at end of file
diff --git 
a/modules/spring/src/test/java/org/apache/ignite/internal/CacheConfigurationQueryEntityXmlTest.java
 
b/modules/spring/src/test/java/org/apache/ignite/internal/CacheConfigurationQueryEntityXmlTest.java
new file mode 100644
index 00000000000..d136fddebca
--- /dev/null
+++ 
b/modules/spring/src/test/java/org/apache/ignite/internal/CacheConfigurationQueryEntityXmlTest.java
@@ -0,0 +1,85 @@
+/*
+ * 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.ignite.internal;
+
+import java.io.File;
+import javax.cache.CacheException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.Ignition;
+import org.apache.ignite.internal.util.typedef.X;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.junit.Test;
+import org.springframework.beans.PropertyAccessException;
+import org.springframework.beans.PropertyBatchUpdateException;
+
+import static 
org.apache.ignite.configuration.CacheConfiguration.MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE;
+import static org.apache.ignite.testframework.GridTestUtils.assertThrows;
+import static org.apache.ignite.testframework.GridTestUtils.resolveIgnitePath;
+
+/** Tests that Spring XML configuration cannot mix indexed types and explicit 
query entities. */
+public class CacheConfigurationQueryEntityXmlTest extends 
GridCommonAbstractTest {
+    /** */
+    private static final String CONFIG_DIR = 
"modules/spring/src/test/config/query-entities/";
+
+    /** Verifies that query entities cannot be configured after indexed types 
through Spring XML. */
+    @Test
+    public void testQueryEntitiesAfterIndexedTypesFails() {
+        assertMixedConfigurationFails(
+            "indexed-types-then-query-entities.xml",
+            "queryEntities"
+        );
+    }
+
+    /** Verifies that indexed types cannot be configured after query entities 
through Spring XML. */
+    @Test
+    public void testIndexedTypesAfterQueryEntitiesFails() {
+        assertMixedConfigurationFails(
+            "query-entities-then-indexed-types.xml",
+            "indexedTypes"
+        );
+    }
+
+    /** */
+    private void assertMixedConfigurationFails(String fileName, String 
propName) {
+        File cfgFile = resolveIgnitePath(CONFIG_DIR + fileName);
+        assertNotNull(cfgFile);
+
+        Throwable err = assertThrows(
+            log,
+            () -> Ignition.loadSpringBean(cfgFile.getAbsolutePath(), 
"cacheConfiguration"),
+            IgniteException.class,
+            null
+        );
+
+        PropertyBatchUpdateException batchErr = X.cause(err, 
PropertyBatchUpdateException.class);
+        assertNotNull(batchErr);
+
+        assertEquals(1, batchErr.getExceptionCount());
+
+        PropertyAccessException propErr = 
batchErr.getPropertyAccessException(propName);
+        assertNotNull(propErr);
+
+        CacheException cause = X.cause(propErr, CacheException.class);
+        assertNotNull(cause);
+
+        assertEquals(
+            String.format(MIXED_QUERY_ENTITIES_API_ERROR_TEMPLATE, 
"query-entity-xml-cache"),
+            cause.getMessage()
+        );
+    }
+}
diff --git 
a/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
 
b/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
index c012cc43542..b151ae40d3a 100644
--- 
a/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
+++ 
b/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
@@ -26,6 +26,7 @@ import org.apache.ignite.cdc.CdcConfigurationTest;
 import org.apache.ignite.cluster.ClusterStateXmlPropertiesTest;
 import org.apache.ignite.encryption.SpringEncryptedCacheRestartClientTest;
 import org.apache.ignite.encryption.SpringEncryptedCacheRestartTest;
+import org.apache.ignite.internal.CacheConfigurationQueryEntityXmlTest;
 import org.apache.ignite.internal.GridFactorySelfTest;
 import org.apache.ignite.internal.GridSpringBeanSerializationSelfTest;
 import org.apache.ignite.internal.IgniteClientSpringBeanTest;
@@ -91,6 +92,8 @@ import org.junit.runners.Suite;
     CdcCommandLineStartupTest.class,
 
     SqlPlanHistoryConfigTest.class,
+
+    CacheConfigurationQueryEntityXmlTest.class,
 })
 public class IgniteSpringTestSuite {
 }

Reply via email to