1

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.

1 Answer 1

1

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)); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.