我在本机查询中遇到了一件奇怪的事情:
如果我尝试使用命名本机查询,如下所示
@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 {
.......
}
答案 0 :(得分: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()?
答案 1 :(得分:0)
从@NamedNativeQuery中删除resultClass。
请参阅https://stackoverflow.com/a/9763489
对于NamedNativeQueries,只有在结果实际映射到实体时才能使用resultClass。