Spring 使用关系 table 从一个 table 获取数据 JPA

Spring Data JPA Fetch from one table using the relationship table

这是我的 USER 实体,USER_GROUP 是与 GROUP 的关系 table。 如何获取所有用户 Where groupid = ?

    @Entity 
    @Table(name="USER") 
    public class User implements Serializable {
      @Id Long userId;
      @ManyToOne 
      @JoinTable(name = "USER_GROUP", 
                joinColumns = @JoinColumn(name = "userid"), 
                inverseJoinColumns = @JoinColumn(name = "groupid")) 
      private List<Group> groups;
    } 

我相信您也在使用 UserRepository。 在您的 UserRepository 中,您可以编写一个方法来获取所有此类数据。

public interface UserRepository extends JpaRepository<User, Long>{

    @Query(value="Select u from User u inner join u.groups group where group.groupid = :groupId ")
    List<User> findAllByGroupId(@Param("groupId") long groupId)

}

这应该有效。不过我还没有测试过。

注意 使用 DISTINCT 到 select 只有唯一的 User 个对象。