The following query was taken from this answer. The only difference is that I need to match against a list of Enumeration values that contain possible attributes that I must filter. In addition the list of values will be dynamically set and may contain between 1 and 10 enumeration values.
select c.*
from comments c
join (
values
("FOO",1),
("BAR",2),
("BAZ",3),
) as x (attribute, ordering) on c.attribute = x.attribute
order by x.ordering
How can I express this nested JOIN
and the VALUE
pairs in a Spring @Query
method of a Spring Data repository? What other options are there to express this query in a Spring application?
I am open for solutions using both Hibernate, JPA or Spring Data (JPA).
Update
I use Comment
to demonstrate the issue, in practice I have a more complex entity. For the purpose of this question lets assume Comment
is defined like this:
@Entity
class Comment {
@Id @GeneratedValue Long id;
String text;
@Enumerated (value = EnumType.STRING)
AttributeEnum attribute; //enum values: FOO, BAR, BAZ
}
Now, I want to select all comments where attribute is either 'BAR'
or 'BAZ'
and I want to specify at runtime that 'BAZ'
comments should be ordered before 'BAR'
comments.
I am looking to implement a function which behaves similar to the following:
Page<Comment> findCommentsByAttributeIn(List<AttributeEnum> attributes,
Pageable pageable);
with the added constraint, that the sorting matches the order of attributes in the list. So if BAZ
comes before BAR
in the list it will be sorted before BAR
.