简体   繁体   中英

fetching multiple entities using HQL

Is it possible to fetch multiple entities using 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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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