Heetola
Heetola

Reputation: 6191

Criteria, how to access a subclass property

weirdly I cannot find something simple about this, I've got 2 entity, one inside an other and my question is how can I access a property from the sub-entity?

entity 1

@Getter
@Setter
@Entity
public class ObjectA{
    String name;
    String surname;
    ObjectB B;
}

entity 2

@Setter
@Getter
@Entity
ObjectB{
    String family;
    String range;
}

what I want is to access familly and range with a criteria search, so I made this :

public List<ObjectA> search(String name, String surname, String family, String range) {
    Criteria c = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(ObjectA.class, "a");

if (!name.equals("")) {
    c.add(Restrictions.eq("a.name", name));
}
if (!surname.equals("")) {
    c.add(Restrictions.eq("a.surname", surname));
}
if (!family.equals("")) {
    c.add(Restrictions.eq("a.B.family", family));
}
if (!range.equals("")) {
    c.add(Restrictions.eq("a.B.range", range));
}
return c.list();

}

name and surname can be accessed but family and range cannot. 'could not resolve property' What should I do?

thanks =D

Upvotes: 4

Views: 4515

Answers (2)

Sebastien
Sebastien

Reputation: 677

In your case I'm not sure that you need aliases. To request on a sub-entity, you need to create a criteria on the sub-entity, then add the parameters on it :

public List<ObjectA> search(String name, String surname, String family, String range) {
    Criteria aCriteria = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(ObjectA.class);

if (!name.equals("")) {
    aCriteria.add(Restrictions.eq("name", name));
}
if (!surname.equals("")) {
    aCriteria.add(Restrictions.eq("surname", surname));
}

Criteria bCriteria = aCriteria.createCriteria("B");

if (!family.equals("")) {
    bCriteria.add(Restrictions.eq("family", family));
}
if (!range.equals("")) {
    bCriteria.add(Restrictions.eq("range", range));
}
return aCriteria.list();

Beware : the aCriteria.createCriteria("B") will make it so that only ObjectA objects that have a non null B will be returned, so you might want to create the sub-criteria only if family and range are not empty.

Upvotes: 2

WeMakeSoftware
WeMakeSoftware

Reputation: 9162

You have to create an alias for the subclass property to be able to access it.

Take a look at section 15.4 of the following manual http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html

Upvotes: 5

Related Questions