Hibernate: Criteria with collections
Asked Answered
T

1

10

I have a problem with hibernate and criterias. I have two Classes:

public class Place{
    long id;
    String name;
    Set<Street> streets;
}

public class Street{
    long id;
    String name;
    Place place;
}

I now want to write a method which returns a list of places with a name like given in parameters and a street named like given in parameters.

public List<Place> findPlaces(String name, String streetname){
    //getSession() gives me a hibernate session
    Criteria crit = getSession().createCriteria(Place.class, "place");
    crit.add(Restrictions.like("name", name+"%"));
    //Everything works fine until here
    //Last step: Sort out all places not containing a street named like streetname + "%"
}

I tried different ways for the last step:

//streetList is a list of all streets named like streetname
crit.add(Restrictions.in("streets", streetList));

Another way:

DetachedCriteria strasseCrit = DetachedCriteria.forClass(Street.class, "street");
streetCrit.add(Restrictions.like("street.name", streetname + "%"));
streetCrit.createAlias("street.place", "streetPlace");
streetCrit.add(Restrictions.eqProperty("streetPlace.id", "place.id"));
streetCrit.setProjection(Projections.property("street.name"));
crit.add(Subqueries.exists(streetCrit));

last way:

crit.createAlias("place.streets", "street");
crit.add(Restrictions.like("street.name", streetname + "%"));
crit.setResultTransformer(DistinctResultTransformer.INSTANCE);

I hope you can understand my problem and sorry for my bad english :(

I searched for a solution for two days and I do not know how to go on...

Greetings form Germany :) Philipp

Tropopause answered 2/4, 2012 at 19:46 Comment(2)
What errors do you get, in particular when using the last way?Rubbing
There was no error, but the returned list had a size of about 300 and only one place, so for example the place 'Munich' occured 300 times in that list. I now know, where the problem was: I allowed the streetname to be empty, so for every street in 'Munich' there was one entry in the list.Brail
C
13
public List<Place> findPlaces(String name, String streetname){
    Criteria crit = getSession().createCriteria(Place.class, "place");
    criteria.createAlias("streets", "s");  // Create alias for streets
    crit.add(Restrictions.like("s.name", name+"%"));
    // continue method
}
Chantry answered 2/4, 2012 at 20:11 Comment(1)
Thank you so much. I also had this solution before, but it did not work because I allowed the streetname to be empty, so for every street in 'Munich' there was one entry in the list. So the list was full of every time the same place :) Shame on me for that stupid mistake:)Brail

© 2022 - 2024 — McMap. All rights reserved.