在JPA查询上映射pojo

问题描述 投票:-1回答:1

假设我有关于jpa的查询,如

@Query(
        value = "SELECT user_no, count(*) " +
                "FROM users " +
                "where status = 'VCS' group by user_task_no",
        nativeQuery = true
)
List<Object> getUsers();

现在我可以得到类似的结果

[
    [
        100,
        2
    ],
    [
        200,
        2
    ],
    [
        300,
        3
    ]
]

但是,我希望结果是

[
    {
        "user_no": 100,
        "count": 2
    },
    {
        "user_no": 200,
        "count": 2
    },
    {
        "user_no": 300,
        "count": 3
    }
]

我试图让一个类像

public class UserCount {
    private Long userNo;
    private Long count;

    public UserCount(Long userNo, Long count) {
        this.userNo = userNo;
        this.count = count;
    }
}

并使其

@Query(
        value = "SELECT new fullpackage.UserCount(user_no, count(*)) " +
                "FROM users " +
                "where status = 'VCS' group by user_task_no",
        nativeQuery = true
)
List<UserCount> getUsers();

但是,我遇到了错误

syntax error at or near "." ...
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

关于如何解决此问题的任何想法?

java sql spring spring-data jpql
1个回答
0
投票
new语法适用于jpql,不适用于sql。您无法将其与nativeQuery一起使用。您将必须执行以下操作:

@Query( "SELECT new fullpackage.UserCount(userTaskNo, count(*)) " + "FROM Users " + "where status = 'VCS' group by userTaskNo" ) List<UserCount> getUsers();

© www.soinside.com 2019 - 2024. All rights reserved.