Skip to content

Commit 2a1f6e3

Browse files
schaudergregturn
authored andcommitted
Support Contains with ElementCollection of type String.
Properly handle `contains` for an ElementCollection of type String in a LIKE query, wrapping the the parameter in wildcards only when needed. Closes: #2607.
1 parent 525cf6a commit 2a1f6e3

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/main/java/org/springframework/data/jpa/repository/query/ParameterMetadataProvider.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,12 @@
1515
*/
1616
package org.springframework.data.jpa.repository.query;
1717

18-
import java.util.*;
18+
import java.util.ArrayList;
19+
import java.util.Arrays;
20+
import java.util.Collection;
21+
import java.util.Collections;
22+
import java.util.Iterator;
23+
import java.util.List;
1924
import java.util.function.Supplier;
2025
import java.util.stream.Collectors;
2126

@@ -192,6 +197,7 @@ static class ParameterMetadata<T> {
192197
private final ParameterExpression<T> expression;
193198
private final EscapeCharacter escape;
194199
private final boolean ignoreCase;
200+
private final boolean noWildcards;
195201

196202
/**
197203
* Creates a new {@link ParameterMetadata}.
@@ -202,6 +208,7 @@ public ParameterMetadata(ParameterExpression<T> expression, Part part, @Nullable
202208
this.expression = expression;
203209
this.type = value == null && Type.SIMPLE_PROPERTY.equals(part.getType()) ? Type.IS_NULL : part.getType();
204210
this.ignoreCase = IgnoreCaseType.ALWAYS.equals(part.shouldIgnoreCase());
211+
this.noWildcards = part.getProperty().getLeafProperty().isCollection();
205212
this.escape = escape;
206213
}
207214

@@ -237,7 +244,7 @@ public Object prepare(Object value) {
237244
return condensedValue;
238245
}
239246

240-
if (String.class.equals(expression.getJavaType())) {
247+
if (String.class.equals(expression.getJavaType()) && !noWildcards) {
241248

242249
switch (type) {
243250
case STARTING_WITH:

src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2829,6 +2829,24 @@ void mergeWithNativeStatement() {
28292829
.map(User::getAge).contains(30);
28302830
}
28312831

2832+
@Test // GH-2607
2833+
void containsWithCollection() {
2834+
2835+
firstUser.getAttributes().add("cool");
2836+
firstUser.getAttributes().add("hip");
2837+
2838+
secondUser.getAttributes().add("hip");
2839+
2840+
thirdUser.getAttributes().add("rockstar");
2841+
thirdUser.getAttributes().add("%hip%");
2842+
2843+
flushTestUsers();
2844+
2845+
List<User> result = repository.findByAttributesContains("hip");
2846+
2847+
assertThat(result).containsOnly(firstUser, secondUser);
2848+
}
2849+
28322850
private Page<User> executeSpecWithSort(Sort sort) {
28332851

28342852
flushTestUsers();

0 commit comments

Comments
 (0)