我正在尝试使用 Spring JPA 存储库创建查询。我有一个项目,其中包含允许访问该项目的组列表。给定一个属于一个或多个组的用户,我想查询项目表并返回用户属于至少一个项目允许的组的所有项目。
@Query("select item from Item item where item.allowedGroups.id in ?1")
Page<Object> findByAllowedGroups(List<Long> userGroupIds, Pageable pageable);
然而,这会导致以下异常:
org.hibernate.QueryException: illegal attempt to dereference collection [item0_.id.allowedGroups] with element property reference [id]
理想情况下,我会在 item.allowedGroups 和 userGroupIds 参数上执行 JOIN,但我无法确定如何在 JPA 查询的参数上执行 JOIN。
本质上,我需要知道推荐的 Spring JPA 查询解决方案是什么,用于确定给定参数中是否至少存在对象列表字段的一个元素。
元素等级:
@Entity
@Table(name = "item")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Item extends AbstractAuditingEntity implements Serializable,Comparable<File> {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany(fetch = FetchType.EAGER)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "item_allowed_groups",
joinColumns = @JoinColumn(name="item_id"),
inverseJoinColumns = @JoinColumn(name="group_id"))
private Set<Group> allowedGroups = Sets.newHashSet();
// getters and setters
团体课:
@Entity
@Table(name = "group")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Group implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(max = 50)
@Column(name = "name", length = 50, nullable = false)
private String name;
// getters and setters
最佳答案
我通过设置 Spring JPA QueryDSL 并在这个 Stack Overflow 答案中实现解决方案解决了这个问题:https://stackoverflow.com/a/33455117/3285398 .我将 BooleanExpression 修改为以下内容:
public static BooleanExpression hasItemAccess(List<Group> groups) {
QItem item = QItem.item;
return item.allowedGroups.any().in(groups);
}
并且在ItemRepository中添加了一个查询方法:
public interface ItemRepository extends JpaRepository<Item,Long>, QueryDslPredicateExecutor<Item> {
@Query("select item from Item item where item.user.login = ?#{principal.username}")
Page<Item> findByUserIsCurrentUser(Pageable pageable);
Page<Item> findAll(Predicate predicate, Pageable pageable);
关于java - Spring JPA 查询检查参数列表中是否至少存在一个列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38233333/