Search code examples
javahibernatealiascriteria

Hibernate Criteria.ALIAS_TO_ENTITY_MAP to ArrayList Student missing


I have one to many relationship I need to fetch eager the associate table as well filters the 2 tables using criteria. Here is my code..

public ArrayList<Student>getListOfStudents() {
Session session = getHibernateTemplate().getSessionFactory().openSession();        
Criteria like = session.createCriteria(Student.class)   
.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
prepareForSelect(like);//some filtering       
Criteria innerCriteria = like.createCriteria("phone","p",JoinType.LEFT_OUTER_JOIN);
prepareForSelect(innerCriteria);//same filtering but in phone now..
like.addOrder(Order.asc("c01"));        
Iterator<java.util.Map<Object,Object>> ite = like.list().iterator();
HashSet<Student>students= new HashSet<Student>();
while(ite.hasNext())
{
    java.util.Map<Object,Object> map = ite.next();
    Student aStudent = (Student)map.get(Criteria.ROOT_ALIAS);
    Phone phone = (Phone)map.get("p");
    if(student.contains(aStudent))        
        students.addPhoneToStudent(phone); //add to phone hashSet in Student.class                       
    else    
   {
        student.setListOfPhones(new HashSet<Phone>(0));
        students.addPhoneToStudent(phone);        
        students.add(student);                                
   }
session.close(); 
return new ArrayList<Student>(students);
}

everything is OK but if a Student dont have a phone which fullfill the criteria restrictions(isValidPhone=true) the Student is not in the resultset i need still the student even if not have a valid phone because the App should be able to add a new phone for the student can somebody give a tip. thank a lot


Solution

  • this worked for me.. basically i was putting the restrictions of the second table (associate) table on the general where (Query Clause) this means the 1 table is being affect it on this restrictions of the 2 table the trick is here. put the restrictions only in the left outer join here is some code.[the restrictions you want in your 2 table.]

    org.hibernate.criterion.Conjunction innerRestrictions = (org.hibernate.criterion.Conjunction)Restrictions.conjunction().add(Restrictions.eq("phoneValid",true)).add(Restrictions.eq("phoneMatch",true));
    

    and then you retrieve all the association in the 2 table here.

    like.createCriteria("phone","p",JoinType.LEFT_OUTER_JOIN,innerRestrictions);
    

    here you are asking to hibernate to create a innerCriteria on the field phone(the many side of the relationship) creates a alias 'p' the fetch is left outer join means the student without phones at all is still on the resultSet and later the restrictions you want to apply to the criteria the innerCriteria hope it helps.