java hibernate标准错误

时间:2013-01-23 10:39:54

标签: java hibernate criteria

这里是数据库架构:

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;
                         }

现在我需要创建一个Criteria来检查表C中的正确'id'和表B中的'comment'。我试着这样做:

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 + "%"));
}

2 个答案:

答案 0 :(得分:1)

我认为代码不会为Criteria的{​​{1}}对象创建代码。此外,代码中还存在语法错误。

<强>修

objectB

语法问题

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));

答案 1 :(得分:0)

试试这个。您不需要两次调用createCriteria(“objectB”)

  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 + "%"));
}