Reputation: 6242
Here the database schema:
Table A: public class A {
id integer, B objectB;
comment varchar(30), String comment;
id_B integer }
Table B: public class B {
id integer, C objectC;
comment varchar(20), String comment;
network integer }
Table C: public class C {
id Integer id;
name varchar(30) String name;
}
Now I need to create a Criteria that checks for the proper 'id' in Table C and the 'comment' in Table B. I tried to do:
Criteria criteria = getSession().createCriteria(A.class);
criteria.createCriteria("objectB")
.createCriteria("objectC").add(Restrictions.idEq(networkID));
//gives org.hibernate.QueryException: duplicate association path: objectB error
if (comment != null && comment.length() > 0) {
criteria.createCriteria("objectB")
.add(Restrictions.like("comment", "%" + comment + "%"));
}
//second approach gives me no error but does not work, means I receive the wrong results
if (comment != null && comment.length > 0) {
criteria.add(Restrictions.like("comment", "%" + comment + "%"));
}
Upvotes: 0
Views: 505
Reputation: 11310
Try this. You do not need to call createCriteria("objectB") two times
Criteria criteria = getSession().createCriteria(A.class);
criteria.createCriteria("objectB").createCriteria("objectC").add(Restrictions.idEq(networkID)).add(Restrictions.like("comment", "%" + comment + "%"));
if (comment != null && comment.length > 0) {
criteria.createAlias("objectB", "b")
criteria.add(Restrictions.like("b.comment", "%" + comment + "%"));
}
Upvotes: 0
Reputation: 94499
I don't think it likes that the code creates to Criteria
objects for objectB
. Also there is a syntax error within the code.
Revised
Criteria criteria = getSession().createCriteria(A.class);
Criteria criteriaB = criteria.createCriteria("objectB");
Criteria criteriaC = criteriaB.createCriteria("objectC");
criteriaB.add(Restrictions.like("comment", "%" + comment + "%"));
criteriaC.add(Restrictions.idEq(networkID));
Syntax Issue
Criteria criteria = getSession().createCriteria(A.class);
criteria.createCriteria("objectB")
.createCriteria("objectC").add(Restrictions.idEq(networkID));
//Syntax error occurs here, missing add
criteria.createCriteria("objectB")
.(Restrictions.like("comment", "%" + comment + "%"));
//Fix
criteria.createCriteria("objectB").add(Restrictions.like("comment", "%" + comment + "%"));
Upvotes: 1