Wrap Criteria is and regex comparison if necessary.
This commit wraps simple values and Patterns if to avoid creating invalid query objects. Original pull request: #4862 Closes #4850
This commit is contained in:
committed by
Mark Paluch
parent
639e2c21f6
commit
da5c062061
@@ -945,8 +945,17 @@ public class Criteria implements CriteriaDefinition {
|
||||
Document queryCriteria = new Document();
|
||||
|
||||
if (!NOT_SET.equals(isValue)) {
|
||||
queryCriteria.put(this.key, this.isValue);
|
||||
queryCriteria.putAll(document);
|
||||
if(document.isEmpty()) {
|
||||
queryCriteria.put(this.key, this.isValue);
|
||||
}
|
||||
else {
|
||||
if(isValue instanceof Pattern || isValue instanceof BsonRegularExpression) {
|
||||
document.put("$regex", isValue);
|
||||
} else {
|
||||
document.put("$eq", isValue);
|
||||
}
|
||||
queryCriteria.put(this.key, document);
|
||||
}
|
||||
} else {
|
||||
queryCriteria.put(this.key, document);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,9 @@ import static org.springframework.data.mongodb.test.util.Assertions.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.bson.BsonRegularExpression;
|
||||
import org.bson.Document;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.geo.Point;
|
||||
@@ -50,6 +52,44 @@ public class CriteriaUnitTests {
|
||||
assertThat(c.getCriteriaObject()).isEqualTo("{ \"name\" : \"Bubba\"}");
|
||||
}
|
||||
|
||||
@Test // GH-4850
|
||||
public void testCombiningSimpleCriteria() {
|
||||
|
||||
Document expected = Document.parse("{ name : { $eq : 123, $type : ['long'] } }");
|
||||
|
||||
Criteria c = Criteria.where("name") //
|
||||
.is(123) //
|
||||
.type(Type.INT_64);
|
||||
|
||||
assertThat(c.getCriteriaObject()).isEqualTo(expected);
|
||||
|
||||
c = Criteria.where("name") //
|
||||
.type(Type.INT_64)
|
||||
.is(123);
|
||||
|
||||
assertThat(c.getCriteriaObject()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test // GH-4850
|
||||
public void testCombiningBsonRegexCriteria() {
|
||||
|
||||
Criteria c = Criteria.where("name")
|
||||
.regex(new BsonRegularExpression("^spring$"))
|
||||
.type(Type.INT_64);
|
||||
|
||||
assertThat(c.getCriteriaObject()).isEqualTo(Document.parse("{ name : { $regex : RegExp('^spring$'), $type : ['long'] } }"));
|
||||
}
|
||||
|
||||
@Test // GH-4850
|
||||
public void testCombiningRegexCriteria() {
|
||||
|
||||
Criteria c = Criteria.where("name")
|
||||
.regex("^spring$")
|
||||
.type(Type.INT_64);
|
||||
|
||||
assertThat(c.getCriteriaObject()).hasEntrySatisfying("name.$regex", it -> assertThat(it).isInstanceOf(Pattern.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEqualCriteria() {
|
||||
Criteria c = new Criteria("name").ne("Bubba");
|
||||
|
||||
Reference in New Issue
Block a user