【问题标题】:Hibernate ClassCastException while comparing int and long在比较 int 和 long 时休眠 ClassCastException
【发布时间】:2015-03-13 10:45:06
【问题描述】:

我有一个包含大约 800 个查询的 HQLquery 文件。在运行时检测到要执行的查询并映射从浏览器传递的参数,默认情况下,我的代码将从浏览器传递的参数转换为 Long。问题是在某些 bean 类中,变量(即比较的左侧)是 int,而在某些情况是龙。但是在运行时我想不出任何方法来检测比较参数左侧的“类型”。

say : select * from employee e where e.id=$empid$

$empid$ 被替换为运行时从浏览器传递的值,默认情况下我的代码将传递的值转换为 Long。如果 e.id 是 int 那么这将抛出 ClassCastException 。有什么方法可以在运行时检测 e.id 的类型。或任何其他解决此问题的想法。

我尝试将 RHS 转换为 Number,但它对我不起作用。任何建议都会非常受欢迎。谢谢

【问题讨论】:

  • 检查EmployeeEntity的ID字段的类是Integer还是Long
  • 我们的 hql 查询被定义为属性文件中的键值对。键作为输入传递,值是字符串格式的实际 HQL 查询。函数的输入是 (NamedQueryKey, ParameterList) 我们在运行时不知道 NamedQueryKey 中传递的查询中涉及的 Bean 是什么,除非我们解析查询(这是我们想要避免的)
  • 然后重写所有实体使用Long作为id列类型

标签: java hibernate jpa orm hql


【解决方案1】:

首先,您需要访问 ClassMetadata:

ClassMetadata metadata=sessionFactory.getClassMetadata(Employee.class);

您编写 HQL 查询如下:

Number id = ...;
Type identifierType = metadata.getIdentifierType();
Class identifierClass = identifierType.getReturnedClass();                                

if(Long.class.equals(identifierClass)) {
    id = id.longValue();
} else {
    id = id.intValue();
}

session.createQuery("select e from Employee e where e.id = :id")
   .setParameter("id", id, identifierType)
   .list();

提供实际类型应该可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 2018-12-18
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多