[英]Map sql query result to java object(in Non-Entity class) using spring jpa
I want to assign SQL query result to Java object which is in non-entity class. 我想将SQL查询结果分配给非实体类中的Java对象。 My query is counting the number of records in Table A mapped to another Table B.
我的查询正在计算映射到另一个表B的表A中的记录数。
@Query(value="select count(a.id) from table1 a join table2 b on a.id=b.id group by a.id", nativeQuery=true)
Non-Entity class 非实体类
public class Sample {
//assign query result to count variable
private long count;
// getters and setters
}
A and B are Entity class, I'm selecting specified columns of Entity A and B and including that columns in Sample.class and sending data as JSON on REST call. A和B是实体类,我选择了实体A和B的指定列,并将这些列包括在Sample.class中,并在REST调用中将数据作为JSON发送。
Now my question is to assign count result to count variable. 现在我的问题是将计数结果分配给count变量。
Thanks in advance 提前致谢
How to do a JPQL query using a "group by" into a projection (Non-Entity-Class)? 如何使用“分组依据”到投影中(非实体类)进行JPQL查询?
Scenario you have two tables: User and User_Role and you want to know how many users in your system has the "public" role and how many have the "admin" role (Any other roles too if present). 方案中有两个表:User和User_Role,并且您想知道系统中有多少个用户具有“公共”角色,有多少个用户具有“ admin”角色(如果存在,则还有其他任何角色)。
For example: I want a query that will let me know there are two users that have "public" role and one user has the "admin" role. 例如:我想要一个查询,让我知道有两个用户具有“公共”角色,一个用户具有“管理员”角色。
Simplest Example: 最简单的例子:
@Query("SELECT ur.roleName, count(u.id) from User u left join u.userRole ur group by ur.roleName")
List<Object[]> getCounts();
In this case dealing with the result is more complicated then you typically would want. 在这种情况下,处理结果会比通常所需的更为复杂。 You would have to iterate over both the list and array of Objects.
您将必须遍历对象的列表和数组。
Query into a projection Example: 查询投影示例:
@Query("SELECT new com.skjenco.hibernateSandbox.bean.GroupResultBean(ur.roleName, count(u.id)) from User u left join u.userRole ur group by ur.roleName")
List<GroupResultBean> getCountsToBean();
This would give you a List that is much better to work with. 这将为您提供一个更好使用的列表。
Code Example: https://github.com/skjenco/hibernateSandbox/blob/master/src/test/java/com/skjenco/hibernateSandbox/repository/UserProjectionExampleTest.java 代码示例: https : //github.com/skjenco/hibernateSandbox/blob/master/src/test/java/com/skjenco/hibernateSandbox/repository/UserProjectionExampleTest.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.