Bahattin Ungormus
Bahattin Ungormus

Reputation: 713

Hibernate: How can I reuse an alias on the same criteria?

I am trying to convert HQL queries to criteria and create aliases to perform join on a criteria as follows:

public List<Patient> getPatients(String ssn, String phone, String zipCode) {
  Criteria c = getCurrentSession().createCriteria(Patient.class);

  if(ssn != null) {
    c.add(Restrictions.eq("ssn", ssn));
  }

  if(phone != null) {
    c.createAlias("contact", "contactAlias1")
    c.add(Restrictions.eq("contactAlias1.phone", phone));
  }

  if(zipCode != null) {
    c.createAlias("contact", "contactAlias2")
    c.add(Restrictions.eq("contactAlias2.zipCode", zipCode));
  }

}

When I run this code I got the following error:

org.hibernate.QueryException: duplicate association path

Of course I can always add another if condition as follows and use single alias:

if(phone != null || zipCode != null) {
  c.createAlias("contact", "contactAlias")
}

However, the actual code has thousands of lines like this. Using this approach would be tedious and make the code unreadable.

So I want to know if I can detect a previously created alias for the same mapping and reuse it for other restrictions.

Upvotes: 1

Views: 2365

Answers (1)

Thierry
Thierry

Reputation: 5440

use a Set to store already defined aliases :

public List<Patient> getPatients(String ssn, String phone, String zipCode) {
  Set<String> definedAliases = new HashSet<String>();
  Criteria c = getCurrentSession().createCriteria(Patient.class);

  if(ssn != null) {
    c.add(Restrictions.eq("ssn", ssn));
  }

  if(phone != null) {
    if (!definedAliases.contains("contact")) {
      c.createAlias("contact", "contactAlias");
      definedAliases.add("contact");
    }
    c.add(Restrictions.eq("contactAlias.phone", phone));
  }

  if(zipCode != null) {
    if (!definedAliases.contains("contact")) {
      c.createAlias("contact", "contactAlias");
      definedAliases.add("contact");
    }
    c.add(Restrictions.eq("contactAlias.zipCode", zipCode));
  }

}

Upvotes: 1

Related Questions