Hibernate converts SQL to criteria

I would like to use criteria for my SQL query. I have 3 tables "house", "person" and a third table "liveIn" to match between house and person.

My sql query "select home.id from home, person live where home.country = 'Japan' and person.id = '15' and liveIn.Homeid = home.id and liveIn.PersonId = person.id"

Help someone a little?

0


source to share


2 answers


Assuming you have tables exposed as Home, Person, and LiveIn objects, then something like this might work:



          session.createCriteria(Home.class)
                .add(Restrictions.eq("country", "Japan"))
                .createAlias("person", "p")
                .add(Restrictions.eq("p.id", "15"))
                .list();

      

+1


source


If you have a reference to a person object, you can use that in your criteria query instead of looking for a person id.

For example:



public List<Home> getHomesForPerson(Person thePerson){

    List<Home> homes = session.createCriteria(Home.class)
                          .add(Restrictions.eq("country", "Japan")
                          .add(Restrictions.eq("person", thePerson)
                          .list();
    return homes;
}

      

+1


source







All Articles