2013-01-23 184 views
0

這裏的數據庫模式:java的休眠標準錯誤

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

現在我需要創建檢查表C正確的「ID」和「評論」表B.我試圖做一個標準:

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

回答

1

我不認爲它喜歡的代碼來創建對象CriteriaobjectB。代碼中還有一個語法錯誤。

修訂

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

語法問題

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

試試這個。你並不需要調用個createCriteria(「對象B」)兩次

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

對不起,我忘了提,第二準則「評論」的,如果子句中只添加如果註釋不爲空,我想你解決方案並更新了我的代碼,但它不起作用 – wasp256

+0

您是否嘗試使用別名?http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-associations –