15

Is there a way to use a "contains" function in a @Query tag? If no, what is the best way to implement this?

Example:

@Query("From User u  where u.roles contains :role")
List<User> findByRole(@Param("role") Role role);

The User class does have a Collection containing their Roles.

Edit: As suggested i tried it with like, the application starts, but when this method gets executed a "not matching expected type" exception occurs.

2 Answers 2

27

Just use the following query and you're done:

@Query("From User u where :role member u.roles")
4
  • can you link to the official doc? Commented Oct 3, 2012 at 11:01
  • What doc do you mean? Of @Query annotation or JPA spec? Commented Oct 3, 2012 at 11:39
  • A specs doc for the 'member' expression. Commented Oct 3, 2012 at 13:16
  • 2
    You can look here. There is a definition of collection_member_expression in this section. Commented Oct 3, 2012 at 15:08
-5

Use the like keyword.

@Query("From User u  where u.roles like :role")
5
  • You want to select all roles with keyword 'role'?
    – Bitmap
    Commented Apr 30, 2012 at 11:54
  • maybe this isn't clear or i guess it's not that easy to implement. I want to get all Users that have the passed in Role. Role is a seperate class an not a String and "u.roles" is a collection holding every Role of the user.
    – KenavR
    Commented Apr 30, 2012 at 11:59
  • 1
    i tried List<User> findByRoles(Role role); and it seems to work fine.
    – KenavR
    Commented Apr 30, 2012 at 12:06
  • If role is a collection then do something like this from User u, Role r where r.roleName like "%administrator%" and r.roleId=u.roleId
    – Bitmap
    Commented Apr 30, 2012 at 12:09
  • The question is about collection membership and not substring
    – lilalinux
    Commented Feb 4, 2017 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.