Java Spring Data JPA:查询多对多
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33438483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Data JPA: query ManyToMany
提问by qwe asd
I have entities User
and Test
我有实体User
和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
?
但是我可以使用哪个查询来查找所有测试userName
?
采纳答案by Tunaki
The following method signature will get you want to want:
以下方法签名将使您想要:
List<Test> findByUsers_UserName(String userName)
This is using the property expressionfeature 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.
这是使用Spring Data JPA的属性表达式功能。签名Users_UserName
将被转换为 JPQL x.users.userName
。请注意,这将对给定的用户名执行完全匹配。
回答by ArslanAnjum
Other answer shows how to achieve desired functionality using function naming technique. We can achieve same functionality using @Query annotation as follows:
其他答案显示了如何使用函数命名技术实现所需的功能。我们可以使用 @Query 注释实现相同的功能,如下所示:
@Query("select t from Test t join User u where u.username = :username")
List<Test> findAllByUsername(@Param("username")String username);