Fix Criteria chaining for Criteria.alike().

This commit fixes an issue where an Example probe would not be added to the criteria chain.

Closes #3544
Original pull request: #3549.
This commit is contained in:
Christoph Strobl
2021-01-29 13:36:06 +01:00
committed by Mark Paluch
parent 1d547ec150
commit e644692a8a
3 changed files with 25 additions and 7 deletions

View File

@@ -620,8 +620,15 @@ public class Criteria implements CriteriaDefinition {
*/
public Criteria alike(Example<?> sample) {
criteria.put("$example", sample);
return this;
if (StringUtils.hasText(this.getKey())) {
criteria.put("$example", sample);
return this;
}
Criteria exampleCriteria = new Criteria();
exampleCriteria.criteria.put("$example", sample);
return registerCriteriaChainElement(exampleCriteria);
}
/**

View File

@@ -139,16 +139,14 @@ public class QueryByExampleTests {
assertThat(result).containsExactlyInAnyOrder(p1, p2, p3);
}
@Test // DATAMONGO-1245
@Test // DATAMONGO-1245, GH-3544
public void findByExampleWithCriteria() {
Person sample = new Person();
sample.lastname = "stark";
Query query = new Query(new Criteria().alike(Example.of(sample)).and("firstname").regex("^ary*"));
List<Person> result = operations.find(query, Person.class);
assertThat(result).hasSize(1);
Query query = new Query(new Criteria().alike(Example.of(sample)).and("firstname").regex(".*n.*"));
assertThat(operations.find(query, Person.class)).containsExactly(p1);
}
@Test // DATAMONGO-1459

View File

@@ -771,6 +771,19 @@ public class QueryMapperUnitTests {
assertThat(document).containsEntry("legacyPoint.y", 20D);
}
@Test // GH-3544
void exampleWithCombinedCriteriaShouldBeMappedCorrectly() {
Foo probe = new Foo();
probe.embedded = new EmbeddedClass();
probe.embedded.id = "conflux";
Query query = query(byExample(probe).and("listOfItems").exists(true));
org.bson.Document document = mapper.getMappedObject(query.getQueryObject(), context.getPersistentEntity(Foo.class));
assertThat(document).containsEntry("embedded\\._id", "conflux").containsEntry("my_items", new org.bson.Document("$exists", true));
}
@Test // DATAMONGO-1988
void mapsStringObjectIdRepresentationToObjectIdWhenReferencingIdProperty() {