Spring Data JPA: query ManyToMany

JavaSpringJpaSpring DataSpring Data-Jpa

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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);

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionqwe asdView Question on Stackoverflow
Solution 1 - JavaTunakiView Answer on Stackoverflow
Solution 2 - JavaArslanAnjumView Answer on Stackoverflow
Solution 3 - JavaRafiView Answer on Stackoverflow