简体   繁体   English

在 JPA 查询上映射 pojo

[英]mapping pojo on JPA query

Supposed I have a query on jpa like假设我对 jpa 有一个查询,例如

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

Now I can get the result like现在我可以得到这样的结果

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

However, I want the result to be但是,我希望结果是

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

I tried to make a class like我试着做一个像

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

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

and make it并使它

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

However, I'm getting an error但是,我收到一个错误

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

any idea on how can I fix this?关于如何解决这个问题的任何想法?

The new syntax works on jpql, not on sql. new语法适用于 jpql,不适用于 sql。 You cannot use it with nativeQuery .您不能将它与nativeQuery一起nativeQuery You would have to do something like this:你必须做这样的事情:

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

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

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