Skip to content

MongoQueryCreator will not create query correctly when passing Pattern Object with options [DATAMONGO-2003] #2871

Closed
@spring-projects-issues

Description

@spring-projects-issues

Rizwan Ishtiaq opened DATAMONGO-2003 and commented

 

Problem

Query created from repository method name convention will not contain the options when passing Pattern object as method parameter

//Following regex we are trying to pass
Pattern regex = Pattern.compile("\\bpattern\\b",Pattern.CASE_INSENSITIVE);

//Following method in repository interface
List<Person> findByFirstNameRegex(Pattern regex);

Prove of problem

// new unit test in org.springframework.data.mongodb.repository.query.MongoQueryCreatorUnitTests

//This test will pass with current implementation
@Test 
public void createsRegexQueryCorrectlyWhenPassingPatternObject() throws Exception {

   final Pattern regex = Pattern.compile("\\bpattern\\b");
   PartTree tree = new PartTree("findByFirstNameRegex", Person.class);
   MongoQueryCreator creator = new MongoQueryCreator(tree, getAccessor(converter, regex), context);

   assertThat(creator.createQuery(), is(query(where("firstName").regex("\\bpattern\\b"))));
}

//Below test will fail with current implementation
@Test
public void createsRegexQueryCorrectlyWhenPassingPatternObjectWithOptions() throws Exception {

   final Pattern regex = Pattern.compile("\\bpattern\\b",Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE);
   PartTree tree = new PartTree("findByFirstNameRegex", Person.class);
   MongoQueryCreator creator = new MongoQueryCreator(tree, getAccessor(converter, regex), context);
   assertThat(creator.createQuery(), is(query(where("firstName").regex("\\bpattern\\b","iu"))));
}

Note: above unit test will assume we have fixed the bug #DATAMONGO-2002

Reason

// in org.springframework.data.mongodb.repository.query.MongoQueryCreator

//Old implementation
private Criteria from(Part part, MongoPersistentProperty property, Criteria criteria, Iterator<Object> parameters) {
...
case REGEX:
   return criteria.regex(parameters.next().toString());
...
}

Solution

// in org.springframework.data.mongodb.repository.query.MongoQueryCreator

//New implementation
private Criteria from(Part part, MongoPersistentProperty property, Criteria criteria, Iterator<Object> parameters) {
...
case REGEX: 
Object param = parameters.next();
return param instanceof Pattern ? criteria.regex((Pattern) param) : criteria.regex(param.toString());
...
}

 


Affects: 1.10.12 (Ingalls SR12), 2.0.7 (Kay SR7), 2.1 M3 (Lovelace)

Issue Links:

  • DATAMONGO-2002 Criteria instances using different regex Patterns are considered equal

Referenced from: pull request #570

Backported to: 2.0.8 (Kay SR8), 1.10.13 (Ingalls SR13)

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions