【问题标题】:JPA query with count aggregate function具有计数聚合函数的 JPA 查询
【发布时间】:2020-06-17 05:20:18
【问题描述】:

我有两个实体 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 获取所有As 及其Bs 计数和Failed 状态。

我已尝试使用以下查询:

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();
}

但是,它不起作用。有人可以在这里帮助我吗?

【问题讨论】:

  • 你有一个A 的默认构造函数,不是吗?
  • 是的,我有。如果我还需要创建任何其他构造函数,我可以创建它们。

标签: hibernate spring-boot spring-data-jpa jpa-2.0 jpa-2.1


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    相关资源
    最近更新 更多