简体   繁体   English

使用HQL获取多个实体

[英]fetching multiple entities using HQL

Is it possible to fetch multiple entities using HQL? 是否可以使用HQL提取多个实体? I find myself writing a lot of code like: 我发现自己编写了很多代码,例如:

obj1 = HQL1;
if (obj1 == null)
  obj2 = HQL2;

So I am wondering if it is possible to fold the obj1 == null check into the HQL query and fetch obj2 at the same time in case the condition is true. 所以我想知道是否有可能将obj1 == null检查折叠到HQL查询中,并在条件为真的情况下同时获取obj2。

EDIT: 编辑:

Consider code like this: 考虑如下代码:

Animal cat, dog = null;
cat = currentSession.createQuery("from Cat where id = 1").uniqueResult();
if (cat == null)
  dog = currentSession.createQuery("from Dog where id = 2").uniqueResult();

My question is whether there is a way to write a single HQL query to fetch both cat and dog at the same time (but only fetch dog if cat is null , of course). 我的问题是,是否有写一个HQL语句来抓取两种方式catdog在同一时间(但只取dog ,如果catnull的,当然)。

As mentioned in the comments to your question, your question really lacks context. 如对您的问题的评论中所述,您的问题确实缺乏上下文。 So its hard to answer. 因此很难回答。

You can perform a polymorphic query. 您可以执行多态查询。 This is specific to Hibernate, not at all part of JPA. 这是特定于Hibernate的,而不是JPA的全部。

List animals = session.createQuery( "from Animal" ).list()

this returns you all Animals, both Cats and Dogs. 这将返回您所有的动物,包括猫和狗。

From there you could construct a restriction as you need. 从那里可以根据需要构造限制。 The problem with the type of restriction you seem to want is that it will likely require a subquery which can often lead to inefficient query plans on the DB server. 您似乎想要的限制类型的问题是,它可能需要一个子查询,这通常会导致DB服务器上的查询计划效率低下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM