Spring Data JPA: query ManyToMany

后端 未结 3 489
庸人自扰
庸人自扰 2020-11-29 05:33

I have entities User and Test

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

@Entity
public class         


        
相关标签:
3条回答
  • 2020-11-29 06:15

    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

    0 讨论(0)
  • 2020-11-29 06:20

    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.

    0 讨论(0)
  • 2020-11-29 06:31

    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);
    
    0 讨论(0)
提交回复
热议问题