views:

93

answers:

1

Hi,

I have three entities ClassA, ClassB and ClassC.

ClassA {
 ...
 @Id
 @GeneratedValue
 @Column(name = "a_id")
 private long id;
 ...
 @OneToMany(cascade={CascadeType.ALL})
 @JoinColumn(name="a_id")
 private List<ClassB> bbb;
 ...
}

ClassB {
 ...
 @ManyToOne
 private ClassC ccc;
 ...
}

ClassC {
 ...
 private String name;
 ...
}

I want to filter by hibernate criteria ClassA by 'name' member of ClassC. So I want to obtain by hibernate criteria list of ClassA objects which have inside ClassC objects with specified name. Problem is that access to ClassC objects is through ClassB list.

I tried something like this but it does not work:

crit.createCriteria("bbb").createCriteria("ccc").add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));

I will be grateful for help.

+1  A: 

You need to use aliases to nest the restrictions:

criteria.createAlias("bbb", "bbb", CriteriaSpecification.LEFT_JOIN);
criteria.createAlias("bbb_ccc", "bbb.ccc", CriteriaSpecification.LEFT_JOIN);
criteria.add(Restrictions.ilike("bbb_ccc.name", name, MatchMode.ANYWHERE));

This will filter results on entity aaa, but won't actually fetch the associated entities (bbb and ccc). To fetch these entities the easiest way is set the mapping annotation parameter to FetchMode.EAGER. But you can also do that dynamically in the code on a per query basis.

Pierre Pretorius