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.