从嵌套列表Spring JpaRepository中检索对象

时间:2018-09-12 08:00:21

标签: java nested spring-data-jpa repository jpql

我有一个存储库

public interface GroupRepository extends JpaRepository<Group, Integer> {
}

确实有一个列表

private List<Item> items;

每个项目具有一个 position 属性

private int position;
  

如何通过了解项目的位置来检索   是否出现在列表之一?

Item.java

public class Item extends PersistedBean{
 private int position;
 private Group group;

 @Column(name = "Position")
  public int getPosition() {
    return position;
  }

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "GroupId", referencedColumnName = "Id")
  public Group getGroup() {
    return group;
  }
}

Group.java

public class Group extends PersistedBean {
 private int position;
 private List<Item> items;

  @Column(name = "Position")
  public int getPosition() {
    return position;
  }

  @OneToMany(cascade = CascadeType.ALL, mappedBy = "group", orphanRemoval = false)
  public List<Item> getItems() {
    return items;
  }

}

1 个答案:

答案 0 :(得分:2)

您可以将查询添加到JpaRepository<Group, Integer>存储库中,类似这样的方法应该起作用:

@Query("SELECT g FROM Group g " + 
       "JOIN g.items i ON i.position IN :p")
List<Group> getGroupsWhenPositionMatchAnyRelatedItem(@Param("p") Integer p);