简体   繁体   English

JPA和聚合函数。 如何使用查询结果?

[英]JPA and aggregate functions. How do I use the result of the query?

I'm new to ORM stuff and I need some help understanding something. 我是ORM的新手,我需要一些帮助来理解一些东西。

Let's assume I have the following standard SQL query: 假设我有以下标准SQL查询:

SELECT *, COUNT(test.testId) AS noTests FROM inspection
LEFT JOIN test ON inspection.inspId = test.inspId
GROUP BY inspection.inspId

which I want to use in JPA. 我想在JPA中使用它。

I have an Inspection entity with a one-to-many relationship to a Test entity. 我有一个与Test实体有一对多关系的Inspection实体。 (an inspection has many tests) I tried writing this in JPQL: (检查有很多测试)我试过在JPQL中写这个:

Query query = em.createQuery("SELECT insp, COUNT(???what???) " +
      "FROM Inspection insp LEFT JOIN insp.testList " +  
      "GROUP BY insp.inspId");

1) How do I write the COUNT clause? 1)如何编写COUNT子句? I'd have to apply count to elements from the test table but testList is a collection, so I can't do smth like COUNT(insp.testList.testId) 我必须将count应用于测试表中的元素,但testList是一个集合,所以我不能像COUNT(insp.testList.testId)那样做smth COUNT(insp.testList.testId)

2) Assuming 1 is resolved, what type of object will be returned. 2)假设1已解决,将返回什么类型的对象。 It will definitely not be an Inspection object... How do I use the result? 它肯定不是检验对象......我如何使用结果?

  1. You can give an alias to the joined entity (with AS ) 您可以为已连接的实体提供别名(使用AS
  2. You can create either a new object, or a List with the returned values 您可以创建新对象或带有返回值的List

So: 所以:

SELECT new com.yourproject.ResultHolder(insp, COUNT(test.testId)) 
    FROM Inspection insp LEFT JOIN  insp.testList AS test GROUP BY insp.inspId

Or 要么

SELECT new list(insp, COUNT(test.testId)) 
    FROM Inspection insp LEFT JOIN  insp.testList AS test GROUP BY insp.inspId

The result is then accessible either as an instance of ResultHolder , or as a java.util.List , where the insp is list.get(0) , and the count is list.get(1) 然后,结果可以作为ResultHolder的实例访问,也可以作为java.util.List ,其中insplist.get(0) ,计数是list.get(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM