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 Cla开发者_高级运维ssA 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.
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.
as CriteriaSpecification.LEFT_JOIN is deprecated now , so you can use org.hibernate.sql.JoinType.LEFT_OUTER_JOIN
criteria.createAlias("bbb", "bbb", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("bbb_ccc", "bbb.ccc", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.ilike("bbb_ccc.name", name, MatchMode.ANYWHERE));
精彩评论