'How to select string contains all substring in JPA
I want to select string from table that contains ALL substrings. For example, I have table CAR_DESCRIPTION that contains raws in colum Desc for example:
tesla is super car
bmw is cool car
opel is budget car
And I want to select first raw (tesla is super car) by this substring (tesla, car).
I try to use:
findAllByDescIn(final Set<String> words);
but i get all this raws because all of them contains word car.
Solution 1:[1]
I done it.
Where word something like: "test cool car".
private List<Phrase> find(final String word) {
final StringBuilder words = new StringBuilder();
Arrays.stream(word.split(" ")).collect(Collectors.toList())
.stream()
.filter(StringUtils::isNotEmpty)
.forEach(s -> {
if (StringUtils.isEmpty(words.toString())) {
words.append("%").append(s);
} else {
words.append("%").append(s).append("%");
}
});
return repository.findAllByEngIn(words.toString());
}
//Need to put words like %car%cool%
@Query(nativeQuery = true, value = "SELECT * FROM Phrases as p WHERE p.eng LIKE (:words)")
List findAllByEngIn(final String words);
Solution 2:[2]
You have a Set<String> from which you want to get all Strings that contain the substring "car", I assume. For this, you can iterate over the entire set, and only select the Strings that contain your desired substring:
public Set<String> getSubsetThatContains(Set<String> input, String sub) {
Set<String> output = new HashSet<>();
for (String string: input) {
if (string.contains(sub)) {
output.add(string);
}
}
return output;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Shneider |
| Solution 2 | WeinSim |
