【发布时间】: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中移除强制转换并在调试器中检查返回的类型...