Skip to content

Add Hint annotation #4339

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-3230-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-benchmarks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-3230-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-3230-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-3230-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.data.mongodb.repository;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;

/**
* Annotation to declare index hints for repository query, update and aggregate operations. The index is specified by
* its name.
*
* @author Christoph Strobl
* @since 4.1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Documented
public @interface Hint {

String value() default "";

/**
* The name of the index to use. In case of an {@literal aggregation} the index is evaluated against the initial
* collection or view. Specify the index either by the index name.
*
* @return the index name.
*/
@AliasFor("value")
String indexName() default "";
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,22 @@
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Documented
@QueryAnnotation
@Hint
public @interface Query {

/**
* Takes a MongoDB JSON string to define the actual query to be executed. This one will take precedence over the
* method name then.
*
* @return empty {@link String} by default.
* @return empty {@link String} by default.
*/
String value() default "";

/**
* Defines the fields that should be returned for the given query. Note that only these fields will make it into the
* domain object returned.
*
* @return empty {@link String} by default.
* @return empty {@link String} by default.
*/
String fields() default "";

Expand Down Expand Up @@ -129,4 +130,21 @@
*/
@AliasFor(annotation = Collation.class, attribute = "value")
String collation() default "";

/**
* The name of the index to use. <br />
* {@code @Query(value = "...", hint = "lastname-idx")} can be used as shortcut for:
*
* <pre class="code">
* &#64;Query(...)
* &#64;Hint("lastname-idx")
* List&lt;User&gt; findAllByLastname(String collation);
* </pre>
*
* @return the index name.
* @since 4.1
* @see Hint#indexName()
*/
@AliasFor(annotation = Hint.class, attribute = "indexName")
String hint() default "";
}
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ protected Object doExecute(MongoQueryMethod method, ResultProcessor processor, C
applyQueryMetaAttributesWhenPresent(query);
query = applyAnnotatedDefaultSortIfPresent(query);
query = applyAnnotatedCollationIfPresent(query, accessor);
query = applyHintIfPresent(query);

FindWithQuery<?> find = typeToRead == null //
? executableFind //
Expand Down Expand Up @@ -225,6 +226,21 @@ Query applyAnnotatedCollationIfPresent(Query query, ConvertingParameterAccessor
accessor, getQueryMethod().getParameters(), expressionParser, evaluationContextProvider);
}

/**
* If present apply the hint from the {@link org.springframework.data.mongodb.repository.Hint} annotation.
*
* @param query must not be {@literal null}.
* @return never {@literal null}.
* @since 4.1
*/
Query applyHintIfPresent(Query query) {

if(!method.hasAnnotatedHint()) {
return query;
}
return query.withHint(method.getAnnotatedHint());
}

/**
* Creates a {@link Query} instance using the given {@link ConvertingParameterAccessor}. Will delegate to
* {@link #createQuery(ConvertingParameterAccessor)} by default but allows customization of the count query to be
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ protected Publisher<Object> doExecute(ReactiveMongoQueryMethod method, ResultPro
applyQueryMetaAttributesWhenPresent(query);
query = applyAnnotatedDefaultSortIfPresent(query);
query = applyAnnotatedCollationIfPresent(query, accessor);
query = applyHintIfPresent(query);

FindWithQuery<?> find = typeToRead == null //
? findOperationWithProjection //
Expand Down Expand Up @@ -269,6 +270,21 @@ Query applyAnnotatedCollationIfPresent(Query query, ConvertingParameterAccessor
accessor, getQueryMethod().getParameters(), expressionParser, evaluationContextProvider);
}

/**
* If present apply the hint from the {@link org.springframework.data.mongodb.repository.Hint} annotation.
*
* @param query must not be {@literal null}.
* @return never {@literal null}.
* @since 4.1
*/
Query applyHintIfPresent(Query query) {

if(!method.hasAnnotatedHint()) {
return query;
}
return query.withHint(method.getAnnotatedHint());
}

/**
* Creates a {@link Query} instance using the given {@link ConvertingParameterAccessor}. Will delegate to
* {@link #createQuery(ConvertingParameterAccessor)} by default but allows customization of the count query to be
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,21 @@ static AggregationOptions.Builder applyMeta(AggregationOptions.Builder builder,
return builder;
}

/**
* If present apply the hint from the {@link org.springframework.data.mongodb.repository.Hint} annotation.
*
* @param builder must not be {@literal null}.
* @return never {@literal null}.
* @since 4.1
*/
static AggregationOptions.Builder applyHint(AggregationOptions.Builder builder, MongoQueryMethod queryMethod) {

if(!queryMethod.hasAnnotatedHint()) {
return builder;
}
return builder.hint(queryMethod.getAnnotatedHint());
}

/**
* Append {@code $sort} aggregation stage if {@link ConvertingParameterAccessor#getSort()} is present.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.mongodb.repository.Hint;
import org.springframework.data.mongodb.repository.Meta;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.Tailable;
Expand Down Expand Up @@ -362,6 +363,27 @@ public String[] getAnnotatedAggregation() {
"Expected to find @Aggregation annotation but did not; Make sure to check hasAnnotatedAggregation() before."));
}

/**
* @return {@literal true} if the {@link Hint} annotation is present and the index name is not empty.
* @since 4.1
*/
public boolean hasAnnotatedHint() {
return StringUtils.hasText(getAnnotatedHint());
}

/**
* Returns the aggregation pipeline declared via a {@link Hint} annotation.
*
* @return the index name (might be empty) or {@literal null} if not present.
* @since 4.1
*/
@Nullable
public String getAnnotatedHint() {

Optional<Hint> hint = doFindAnnotation(Hint.class);
return hint.map(Hint::indexName).orElse(null);
}

private Optional<String[]> findAnnotatedAggregation() {

return lookupAggregationAnnotation() //
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ private AggregationOptions computeOptions(MongoQueryMethod method, ConvertingPar
AggregationUtils.applyCollation(builder, method.getAnnotatedCollation(), accessor, method.getParameters(),
expressionParser, evaluationContextProvider);
AggregationUtils.applyMeta(builder, method);
AggregationUtils.applyHint(builder, method);

return builder.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions.Builder;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.convert.MongoConverter;
Expand Down Expand Up @@ -178,6 +179,7 @@ private AggregationOptions computeOptions(MongoQueryMethod method, ConvertingPar
AggregationUtils.applyCollation(builder, method.getAnnotatedCollation(), accessor, method.getParameters(),
expressionParser, evaluationContextProvider);
AggregationUtils.applyMeta(builder, method);
AggregationUtils.applyHint(builder, method);

return builder.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.repository.Hint;
import org.springframework.data.mongodb.repository.Meta;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Update;
Expand Down Expand Up @@ -458,7 +459,7 @@ void collationParameterShouldNotBeAppliedWhenNullOverrideAnnotation() {
void updateExecutionCallsUpdateAllCorrectly() {

when(terminatingUpdate.all()).thenReturn(updateResultMock);

createQueryForMethod("findAndIncreaseVisitsByLastname", String.class, int.class) //
.execute(new Object[] { "dalinar", 100 });

Expand All @@ -469,6 +470,29 @@ void updateExecutionCallsUpdateAllCorrectly() {
assertThat(update.getValue().getUpdateObject()).isEqualTo(Document.parse("{ '$inc' : { 'visits' : 100 } }"));
}

@Test // GH-3230
void findShouldApplyHint() {

createQueryForMethod("findWithHintByFirstname", String.class).execute(new Object[] { "Jasna" });

ArgumentCaptor<Query> captor = ArgumentCaptor.forClass(Query.class);
verify(withQueryMock).matching(captor.capture());
assertThat(captor.getValue().getHint()).isEqualTo("idx-fn");
}

@Test // GH-3230
void updateShouldApplyHint() {

when(terminatingUpdate.all()).thenReturn(updateResultMock);

createQueryForMethod("findAndIncreaseVisitsByLastname", String.class, int.class) //
.execute(new Object[] { "dalinar", 100 });

ArgumentCaptor<Query> captor = ArgumentCaptor.forClass(Query.class);
verify(executableUpdate).matching(captor.capture());
assertThat(captor.getValue().getHint()).isEqualTo("idx-ln");
}

private MongoQueryFake createQueryForMethod(String methodName, Class<?>... paramTypes) {
return createQueryForMethod(Repo.class, methodName, paramTypes);
}
Expand Down Expand Up @@ -584,8 +608,12 @@ private interface Repo extends MongoRepository<Person, Long> {
@org.springframework.data.mongodb.repository.Query(collation = "{ 'locale' : 'en_US' }")
List<Person> findWithWithCollationParameterAndAnnotationByFirstName(String firstname, Collation collation);

@Hint("idx-ln")
@Update("{ '$inc' : { 'visits' : ?1 } }")
void findAndIncreaseVisitsByLastname(String lastname, int value);

@Hint("idx-fn")
void findWithHintByFirstname(String firstname);
}

// DATAMONGO-1872
Expand Down
Loading