Using Hibernate Criteria API, how to query for a subproperty of a property that exists only for certain property types
Asked Answered
R

1

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

Renaldorenard answered 30/11, 2016 at 2:21 Comment(1)
Possible duplicate of Java / Hibernate: Could not resolve property with nested object criteriasApiece
T
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)
Tipper answered 2/12, 2016 at 17:59 Comment(1)
That's not Criteria API.Renaldorenard

© 2022 - 2024 — McMap. All rights reserved.