具有计数聚合函数的 JPA 查询

JPA query with count aggregate function

我有两个实体 AB,如下所示:

@Entity
public class A {
   @Id
   private int id;
   private String name;
   private boolean hasFailedChild;

   @OneToMany
   private List<B> bs;

   public A(String name, long count) {
      this.name = name;
      this.hasFailedChild = (count > 0);
   }
}

@Entity
public class B {
   @id
   private int id;
   private String name;
   private String status;
   @ManyToOne
   private A a;

   //required constructors
}

我正在尝试使用 @Query.

获取所有 A 及其具有 Failed 状态的 B 计数

我已尝试使用以下查询:

public interface ARepository extends CrudRepository<A, Integer> {

   @Query(value = "select new A(a.name, count(b)) " +
            "from A a left join a.bs b where b.status = 'Failed'")
   List<A> findAllA();
}

但是,它不起作用。有人可以帮我吗。

您应该按以下方式更正您的查询:

select new A(a.name, count(b))
from A a
left join a.bs b
where b.status = 'Failed'
group by a.name

有关更多详细信息,请参阅 documentation