【问题标题】:Checking exact match in collection with Spring JPA使用 Spring JPA 检查集合中的完全匹配
【发布时间】:2020-07-15 22:16:59
【问题描述】:

我有一个查询来检查集合是否不包含某些元素然后返回结果,但我想知道是否有更好的方法来使用本机 SQL 或 JPQL 编写它

  @Query("from User u where ?1 not member of u.roles and ?2 not member of u.roles and ?3 not member of u.roles")
  List<User> findAllByRolesIn(Role role1, Role role2, Role role3);

我尝试使用 Set 并将其作为参数传递以通过此操作进行检查

@Query("from User u where ?1 member of u.roles")
List<User> findAllByRolesIn(Set<Role> roles); // where the three roles are in the set

我也尝试使用innot in,但无法使用。

【问题讨论】:

    标签: sql spring-boot jpa spring-data-jpa jpql


    【解决方案1】:

    参见此处第 10.2.3.6 节 https://docs.oracle.com/html/E13946_04/ejb3_langref.html#ejb3_langref_collection_dec

    我认为你需要使用这样的东西:

    select distinct u from User u join u.roles r where r in ?1
    

    【讨论】:

    • 感谢您的建议,但是这不会返回所需的结果。
    • 出于好奇,它返回了什么?
    • Role 在您的代码中是什么样的?是类还是枚举?
    • 它返回一个具有 Role4 和 Role1 的用户列表,但我希望它只返回具有 Role4 的用户。如果用户同时拥有 Role4 和 Role1,则不应选择它们。角色是一个 Pojo,有一个字段 String name
    猜你喜欢
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2021-05-31
    • 2015-02-22
    • 2018-10-20
    • 2011-12-19
    • 2021-08-26
    • 2014-11-01
    相关资源
    最近更新 更多