java - 带有类名的 JPA/Hibernate 查询?

标签 java hibernate orm

在这个例子中 com.test.Cat延伸com.test.Animal并且没有字段 DBCAT com.test.Cat 的表格明确定义它的类型(不是我做的)。

当我从数据库中查询我的动物时,我得到了一个动物集合。

可以按类名对它们进行排序:

order by r.class

但是有没有办法使用类名作为标准呢?例如,我想让所有动物都期待狗。但运气不好 - 即使这样也行不通:

where r.class = ?      (String "ccc.test.Cat")

当我遇到异常时:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at org.hibernate.type.IntegerType.set(IntegerType.java:64)
    at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:154)
    at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:136)
    at org.hibernate.param.PositionalParameterSpecification.bind(PositionalParameterSpecification.java:62)
    at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:514)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1589)
    at org.hibernate.loader.Loader.doQuery(Loader.java:696)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2228)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125)
    at org.hibernate.loader.Loader.list(Loader.java:2120)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:361)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1148)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:67)

最佳答案

根据chapter 14.9的文档,你不应该使用双引号:

The special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.

from Cat cat where cat.class = DomesticCat

关于java - 带有类名的 JPA/Hibernate 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2317590/

相关文章:

java - 预期类型 : java. lang.Integer,实际值 : org. hibernate.id.IdentifierGeneratorHelper$2

mysql - 简单的 hibernate 不起作用,但级联查询可以

php - 我可以使用同一张表以不同方式/以更 Cake 的方式重构我的多个用户类型的设置吗?

java - 如何根据每个请求使用/不使用缓存?

spring - org.springframework.orm.hibernate4.HibernateSystemException : Unknown service requested [org. hibernate.stat.spi.StatisticsImplementor];

java - 如何将外部消息代理添加到 Wildfly?

java - 为什么我在没有使用 android.os.CountDownTimer 调用 Looper.prepare() 的线程中得到一个 "Can' t 创建处理程序?

java - Hibernate 缓存和数据库一致性

java - 如何使用来自多个模块的依赖项构建 Uber jar

java - 使用 JDBC 中的 Postgres 准备好的语句失败,错误代码为 "there is no parameter $1"