Hibernate Criteria for entity with embedded objects

Biman Tripathy picture Biman Tripathy · Dec 23, 2012 · Viewed 7.7k times · Source

I have an entity "UserDetails" which has the following variables:

  1. String userId
  2. String userName
  3. UserContact userContact (where UserContact is an Embeddable class)

UserContact has the following variables:

  1. String phoneNumber
  2. String email
  3. String city

What will be a Hibernate Criteria for fetching the following list:

Users with userName = 'sam' and with city = 'New York'

I tried the following and got the runtime exception that it doesn't recognize the variable 'city':

List<UserLogin> list = session.createCriteria(UserLogin.class)
    .add(Restrictions.eq("userName","sam"))
    .add(Restrictions.eq("city", "New York"))
    .list();

Answer

Biman Tripathy picture Biman Tripathy · Dec 23, 2012

Oh I figured it out...

List<UserLogin> list = session.createCriteria(UserLogin.class)
   .add(Restrictions.eq("userName","sam"))
   .add(Restrictions.eq("userContact.city", "New York"))
   .list();

Silly, just needed to add 'userContact.city' instead of 'city', where userContact is the object of the class UserContact in my entity.