如何在JPA 2.0中创建'类似'的查询实例? [英] How to create an 'instance of' -like query in JPA 2.0?
问题描述
假设我们有一个抽象的@Entity Animal,以及几个扩展Animal的实体类,包括Dog,Cat,Monkey和Bat。
Say we've got an abstract @Entity Animal, and several entity classes that extend Animal, including Dog, Cat, Monkey and Bat.
我如何过滤结果基于扩展实体的类?
How can I filter the results based on the extending entity's class?
示例:
有复选框,用户可以选择要检索的实体。
Example: There are checkboxes where the user can select which entities to retrieve.
[ ] Dog
[X] Cat
[X] Monkey
[ ] Bat
现在我想检索动物
类。我可以在查询中放入什么样的查询参数,以便只返回Cat和Monkey对象?
Now I want to retrieve the entities with a (Named)Query defined in the Animal
class. What kind of query parameters can I put into the query so that only the Cat and Monkey objects will be returned?
推荐答案
我'我不完全确定它是由JPA支持的,但是在Hibernate中这样做的方式,无论继承策略如何,因此即使你没有鉴别器(或者没有将它作为属性映射)也是使用隐式类
属性:
I'm not absolutely sure it's supported by JPA, but the way to do it in Hibernate, regardless of the inheritance strategy, and thus even if you don't have a discriminator (or didn't map it as a property) is to use the implicit class
property :
String jpql = "select a from Animal a where a.class in (:classes)";
Query q = em.createQuery(jpql).setParameter("classes",
Arrays.asList(Cat.class, Monkey.class));
编辑:
我刚刚在JPA2中发现使用TYPE运算符:
I just found it's possible in JPA2 using the TYPE operator :
String jpql = "SELECT a FROM Animal a WHERE TYPE(a) IN :classes";
Query q = em.createQuery(jpql).setParameter("classes",
Arrays.asList(Cat.class, Monkey.class));
这篇关于如何在JPA 2.0中创建'类似'的查询实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!