我正在尝试编写 HQL 请求,但出现异常。有人可以帮助我吗?

Posted

技术标签:

【中文标题】我正在尝试编写 HQL 请求,但出现异常。有人可以帮助我吗?【英文标题】:I am trying to write HQL request, but I get an Exception. Can somebody help me? 【发布时间】:2021-12-23 10:06:10 【问题描述】:

我使用 Hibernate 和 HQL。我需要计算用户阅读了多少本书。 我在我的 DAO 层中编写了这段代码

public int howManyBooksUserRead(int userId) 
            Session session = sessionFactory.openSession();
            Query query = session.createQuery("select' " + userId + " ', count(id) as numberOfBooks from BookOrder where returnDate is not null group by ' " + userId + " ' order by numberOfBooks desc");
            int result = (int) query.getSingleResult();
            session.close();
            return result;
        

结果

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class java.lang.Integer ([Ljava.lang.Object; and java.lang.Integer are in module java.base of loader 'bootstrap')
    at com.web.club3.dao.impl.BookOrderDAOImpl.howManyBooksUserRead(BookOrderDAOImpl.java:102)
    at com.web.club3.service.impl.BookOrderServiceImpl.howManyBooksUserRead(BookOrderServiceImpl.java:74)
    at Main.main(Main.java:25)

【问题讨论】:

@SlavaMedvediev 我应该能够动态更改用户 ID(它必须作为参数)。我怎样才能正确地做到这一点? @Luisa 您的查询有很多问题。尝试将select :userId, count(id) as numberOfBooks from BookOrder where returnDate is not null group by :userId order by numberOfBooks desc 插入数据库工具,该工具允许您设置参数并使用它,直到获得所需的输出。 哦,不要在查询中使用字符串连接。 SQL 注入攻击令人讨厌。 @TheHeadRush 我试过这种方式(“选择 id,count(id) as numberOfBooks from BookOrder where returnDate is not null and id = :userId group by id order by numberOfBooks desc”)但我仍然得到ClassCastException @Luisa 你的结果不是一个integer。从getSingleResult 中移除强制转换并在调试器中检查返回的类型... 【参考方案1】:

此类查询的规范方法是:

TypedQuery<Long> query = session.createQuery("select count(id) as numberOfBooks from BookOrder where returnDate is not null AND id = :userId group by id", Long.class);
query.setParameter("userId", 32);
Long result = query.getSingleResult();

我删除了order by,因为它在计数查询的情况下并不重要。

要启用查询日志记录并调试查询,请添加:

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.type=trace

这应该会为您提供大量日志,包括已执行的 SQL 语句。

【讨论】:

我没有得到正确的结果!我确信 ID 为 3 的用户读了三本书,但我得到了 1 我用 Workbench 测试了查询,我得到了 3,但在 IDEA 中我得到了 1( 至少查询正常工作 :-) 您可以在休眠中启用查询日志记录并比较生成的 SQL。我猜如果用户 ID 相同并且查询相同,它应该返回结果相同。 非常感谢)我没有注意到使用订单 ID 而不是用户 ID)你救了我两次:-)

以上是关于我正在尝试编写 HQL 请求,但出现异常。有人可以帮助我吗?的主要内容,如果未能解决你的问题,请参考以下文章

单元测试给出 NullPointerException

HQL 异常 (org.hibernate.dialect.Dialect$3)

休眠 HQL 到条件

从空列返回实体后出现空指针异常

我正在尝试将 Object 转换为动态类型,但转换失败并出现 RunTimeBinder 异常

烦人的线程异常,有啥办法可以禁用它们?