2

我在原生查询中遇到了一件奇怪的事情:

如果我尝试使用如下命名的本机查询

@NamedNativeQuery(name = "native_count_avg_guest_quizzes", resultClass = java.math.BigDecimal.class, query = "select avg(c) as r from ((select count(*) as c from user_quiz uq join user u on (uq.user_id = u.id) where u.status = 'temporary' group by u.id) as res)")

该应用程序无法运行,我有

org.hibernate.HibernateException: Errors in named queries: native_count_avg_guest_quizzes_

但是,如果我不使用 NamedNativeQuery 并且仅创建如下动态本机查询,则相同的查询可以正常工作:

entityManager.createNativeQuery(
                        "select avg(c) as r from ((select count(*) as c from user_quiz uq join user u on (uq.user_id = u.id) where u.status = 'temporary' group by u.id) as res)")
                        .getSingleResult()

为什么?我对 NamedNativeQuery 做错了什么?谢谢

更新: 实体类如下

@Entity
@Table(name = "user_quiz")
@NamedNativeQueries({
    @NamedNativeQuery(name = "native_count_avg_guest_quizzes", resultClass = java.math.BigDecimal.class, query = "select avg(c) as r from ((select count(*) as c from user_quiz uq join user u on (uq.user_id = u.id) where u.status = 'temporary' group by u.id) as res)")
})
@NamedQueries({
    @NamedQuery(name = "list_clients_quizzes", query = "select uq from UserQuiz uq where uq.quiz.client.id = :clientId"),
    .......
})
public class UserQuiz extends Measurable {
.......
}
4

2 回答 2

4

createNativeQuery用于本地SQL查询语言,这意味着 DB 可以理解并执行该查询(例如,select * from some_table where id = '0001');

它可能会导致数据库依赖。现在您正在使用JPQL语言,这就是为什么使用createQuery()createNameQuery()带有@NameQuery注释的原因。

例子 :

@NameQuery

@NamedQuery(name = "findAllEmployee", query = "select e from Employee e")
@Entity
public class Employee {
    @Id int id;
    String name;
    // ...
}

Query query = em.createNamedQuery("findAllEmployee");
query.getResultList()

动态的

    Query query = em.createQuery("select e from Employee e");
    query.getResultList()?

*本机

Query query = em.createNativeQuery("SELECT * FROM EMPLOYEE_TBL");
query.getResultList()?
于 2012-10-19T06:52:47.867 回答
0

从 @NamedNativeQuery 中删除 resultClass。

https://stackoverflow.com/a/9763489

对于 NamedNativeQueries,您只能在结果实际映射到实体时使用 resultClass。

于 2016-11-08T02:56:20.733 回答