如何创建'实例JPA 2.0中的类似查询? [英] How to create an 'instance of' -like query in JPA 2.0?

查看:41
本文介绍了如何创建'实例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

现在,我想使用在 Animal 类中定义的(Named)Query检索实体.我可以在查询中输入什么样的查询参数,以便仅返回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中做到这一点,即使您不这样做也是如此.没有鉴别符(或没有将其映射为属性)是使用隐式的 class 属性:

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));

我刚刚发现可以使用TYPE运算符在JPA2中使用它:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆