Search code examples
javahibernatecriteria

How to create restriction between two different aliases on Hibernate Criteria query?


I need to make a restriction eq with two aliases, like this:

final Criteria query = sessionFactory.getCurrentSession().createCriteria(Client.class);
query.createAlias("clientPlan", "clientPlanAlias");
query.createAlias("clientOldPlan", "clientOldPlanAlias");
...

query.add(Restrictions.eq("clientPlanAlias.category", "clientOldPlanAlias.category");

Client has a list of clientOldPlans (OneToMany relationship), and one clientPlan (OneToOne). ClientOldPlan and ClientPlan are different classes, but have in common the category attribute, so I want to get the ClientPlans that have the same category as ClientOldPlans

This restriction doesn't work as hibernate tries to match clientPlan.category with the string "clientOldPlanAlias.category".

What's the right way to do this restriction?


Solution

  • Have you tried to use the Restrictions.eqProperty method? I believe this is what you're looking for.

    final Criteria query = sessionFactory.getCurrentSession().createCriteria(Client.class);
    query.createAlias("clientPlan", "clientPlanAlias");
    query.createAlias("clientOldPlan", "clientOldPlanAlias");
    ...
    
    query.add(Restrictions.eqProperty("clientPlanAlias.category", "clientOldPlanAlias.category");