Spring Data JPA: query ManyToMany

I was using @JoinTable and I got it working with this :

@Query("select t from Test t join t.users u where u.username = :username")
List<Test> findAllByUsername(@Param("username") String username);

t.users u instead of User u


The following method signature will get you want to want:

List<Test> findByUsers_UserName(String userName)

This is using the property expression feature of Spring Data JPA. The signature Users_UserName will be translated to the JPQL x.users.userName. Note that this will perform an exact match on the given username.


Other answer shows how to achieve desired functionality using function naming technique. We can achieve same functionality using @Query annotation as follows:

@Query("select t from Test t join User u where u.username = :username")
List<Test> findAllByUsername(@Param("username")String username);