I find Criteria + Example is a good way to implement most query. But I happen a query and I do not know how to use Example to query.
Class A join B, C, D with many-to-one or one-to-one association. A query codition include sample data of Class A, B, C, D.
I try this way to query
Code:
Session s = super.currentSession();
Criteria crit = s.createCriteria(A.class);
crit.add(Example.create(a));
if (a.getB() != null) {
crit = crit.createCriteria("b")
.add(Example.create(a.getB()));
}
if (a.getC() != null) {
crit = crit.createCriteria("c")
.add(Example.create(a.getC()));
}
...
It is ok when createCriteria("b"), but can not continue createCriteria("c").
I also try this:
Code:
Criteria crit = s.createCriteria(A.class);
crit.add(Example.create(a));
crit
.createAlias("b","b")
.createAlias("c","c");
if (searchModel.getB() != null) {
crit.add(net.sf.hibernate.expression.Expression.eq(
"mt.id", searchModel.getMaterial().getId()));
}
...
But it seems can not use Example to alias object.
Is there a better way?