Spring Data JPA: query ManyToMany

qwe asd picture qwe asd · Oct 30, 2015 · Viewed 35.2k times · Source

I have entities User and Test

@Entity
public class User {
    private Long id;
    private String userName;
}

@Entity
public class Test {
    private Long id;

    @ManyToMany
    private Set<User> users;
}

I can get all tests by User entity:

public interface TestRepository extends JpaRepository<EventSettings, Long> {
    List<Test> findAllByUsers(User user);
}

But which query can I use for finding all tests by userName?

Answer

Tunaki picture Tunaki · Oct 30, 2015

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.