Java/JPA |指定继承类型的查询
我正在通用表“Sample”上构建查询,并且我有几种继承自该表“SampleOne”、“SampleTwo”的类型。 我需要这样的查询:
select s from Sample where s.type = :type
其中 type 是表的鉴别器值。是否可以以任何方式(并避免创建特定于实体的查询,每个 SampleOne、SampleTwo ... 等一个查询)
我将非常感谢此主题中的任何输入,
亲切的问候, P。
I am building a query on a generic table "Sample" and I have several types which inherit from this table "SampleOne", "SampleTwo".
I require a query like :
select s from Sample where s.type = :type
where type would be a discriminator value of the table. Is it possible in any way ( and avoid to create an entity specific queries, one for each SampleOne, SampleTwo... etc )
I would greatly appreciate any input in this topic,
Kind regards,
P.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 JPA 2.0 中,您可以使用
TYPE
表达式(尽管目前它不适用于 Hibernate 中的参数,请参阅 HHH-5282):类似的 Hibernate 特定表达式是
.class
:In JPA 2.0 you can use
TYPE
expression (though currently it doesn't work with parameters in Hibernate, see HHH-5282):The similar Hibernate-specific expression is
.class
:以下是Java EE 6 教程的相关部分:
如果我没读错,您的查询:
如果
type
是鉴别器列,则应该仅返回指定子类型的元素,因此您唯一要做的就是进行强制转换结果列表为您请求的子类型。Here's the relevant section of the Java EE 6 tutorial:
If I read this right, your query:
Should only return elements of the specified subtype if
type
is the discriminator column, so the only thing that's left for you to do is to cast the result list to your requested sub type.在 Hibernate 4.3.7 中你仍然要小心,因为
TYPE()
的实现仍然存在问题,例如:此查询不起作用,因为它错误地检查了 < code>SpoForeignPilot 而不是文档的类型。
您可以通过执行以下操作来解决此问题:
You still have to be carefull in Hibernate 4.3.7, because there is still an issue with the implementation of
TYPE()
, for example:This query doesn't work as it incorrectly checks the type of
SpoForeignPilot
and not the type of the document.You can workaround this issue by doing something like this:
在您的存储库中执行此操作
,其中
BaseUserEntity
是您的父实体Do this in your repository
Where
BaseUserEntity
is your parent entity