Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria for entity with embedded objects

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();
like image 515
Biman Tripathy Avatar asked Dec 23 '12 22:12

Biman Tripathy


People also ask

Can embedded class be used as primary key?

The embedded class is embedded in an entity and is mapped to the same database table as the entity. Therefore, unlike the entity, the embedded class does not have a primary key. When using the embedded class, the user specifies @Embeddable in the embedded class.

How do you write criteria in hibernate?

Criteria cr = session. createCriteria(Employee. class); Criterion salary = Restrictions.gt("salary", 2000); Criterion name = Restrictions. ilike("firstNname","zara%"); // To get records matching with OR conditions LogicalExpression orExp = Restrictions.or(salary, name); cr.

What is embedded object in hibernate?

With Hibernate we can use the @Embeddable annotation to mark a class to be eligible as an embeddable class. We can use the @Embedded annotation to embed an embeddable class. The attributes of an embedded class can be overridden using the @AttributeOverrides and the @AttributeOverride annotations.

What is restriction in hibernate criteria?

The Criteria interface makes it easy to selectively fetch the data on the basis of conditions in the select query. The Restriction class in hibernate provide several methods that can be used as conditions (also known as Criterion). These conditions are added to a criteria object with the add() method.


1 Answers

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.

like image 199
Biman Tripathy Avatar answered Sep 18 '22 13:09

Biman Tripathy