8

Consider classes Account, RealAccount, VirtualAccount, and Operation such that:

class Account { }
class RealAccount extends Account { String name; }
class VirtualAccount extends Account { }
class Operation { Account account; }

This means that:

  1. Only RealAccount has a field called name.
  2. Operation's account can be RealAccount or VirtualAccount.

I want to query for all Operations that belong to a RealAccount with a specific name:

session.createCriteria(Operation.class)
   .createAlias("account", "_account")
   .add(Restrictions.eq("_account.name", "Alice"))
   .list();

This fails.

My question: Using the "old" Hibernate Criteria API, how can I query for the account name that exists only when the Operation's account is a RealAccount? Maybe something envolving DetachedCriteria and Subqueries...

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
Marcelo Glasberg
  • 29,013
  • 23
  • 109
  • 133
  • Possible duplicate of [Java / Hibernate: Could not resolve property with nested object criterias](https://stackoverflow.com/questions/1722539/java-hibernate-could-not-resolve-property-with-nested-object-criterias) – Kukeltje Aug 08 '19 at 09:00

1 Answers1

0

You can reference name on RealAccount in a subquery (below example uses HQL, but a Criteria equivalent should be straightforward):

select op from Operation op
where op.account.id in
  (select id from RealAccount where name = :name)
Community
  • 1
  • 1
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110