'JPA Specification, using like againt List<String>
I'm having a problem to use like on List field.
Entity class:
@Entity
public class ToSearch{
@Convert(converter = CollectionConverter.class)
private List<String> myList;
//... OTHER FIELDS ...
}
The converter class:
public class CollectionConverter implements AttributeConverter<List<Object>, String> {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(List<Object> object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
return "";
}
}
@Override
public List<Object> convertToEntityAttribute(String data) {
try {
return objectMapper.readValue(data, new TypeReference<List<Object>>() {
});
} catch (Exception e) {
return null;
}
}
}
And a simple specification:
predicates.add(criteriaBuilder.like(criteriaBuilder.lower(root.get("myList")), "%"+ term + "%")));
My goal is simple, just search a term string, treating this as a simple String.
In fact, in database, myList is a String and like search works fine.
But... When I execute this...
Parameter value [%BLA%] did not match expected type [java.util.List (n/a)]
Any ideas?
Solution 1:[1]
Finally, as the error says, I need to change the field I'm searching for to a compatible kind of data.
criteriaBuilder.like(criteriaBuilder.lower(root.get("myList").as(String.class)), "%" + term + "%")));
Doing this, JPA treats myList as a string, there is no incompatible types any more.
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 | marc_s |