2013-10-25 45 views
0
criteria = createCriteria("employee"); 
criteria.add(Restrictions.eq("name", "Jack")); 
criteria.createAlias("certificate", "cert"); 
criteria.add(Restrictions.eq("cert.certType", "MSFT")); 

criteriaList = criteria.list(); 

下面給出的數據,我覺得上面的查詢應返回一個包含證書的集(集大小= 2)一個記錄,但我得到了相同的記錄重複兩次(一次對於證書表中的每條記錄)。這是爲什麼發生?的Hibernate查詢/標準返回重複數據

EMPLOYEE表:

EMP_ID   NAME  
123    Jack         
111    Mary    
000    Larry 

證書表數據

emp_id  certificate_type seq_no 
123   MSFT     1 
123   MSFT     2 
111   English    1 

employee.hbm.xml

<class name="com.Employee" table="Employee" entity-name="employee" mutable="false"> 
     <cache usage="read-only"/> 
     <id name="id" column="employee_id"/> 
     <set name="certificate" fetch="select" inverse="true" lazy="false" > 
      <key column="employee_id" /> 
      <one-to-many class="com.Certificate" entity-name="CertificateType"/> 
     </set> 
</class>  

certificate.hbm.xml

<class name="com.Certificate" table="Certificate" entity-name="CertificateType" mutable="false"> 
    <cache usage="read-only"/> 
    <composite-id class="com.usps.nom.tops.model.impl.DispatchLegPKImpl" mapped="true"> 
      <key-property name="empId" column="emp_id" /> 
      <key-property name="seqNo" column="SEQ_NO" /> 
    </composite-id> 
    <property name="certType" column="certificate_type"/> 
</class> 

的POJO

public class Employee { 
    private int id; 
    private String ame; 
    //getters and setters 
    public boolean equals(Object obj){} 
} 
public class Certificate { 
    private int emp_id; 
    private String certType; 
    private String seqNo; 
    //getters and setters 
    public boolean equals(Object obj){} 
    } 

編輯: 如果我把結果(即criteriaList在我的例子)在一組,那麼它擺脫的重複記錄。

Set<Employee> empSet = new HashSet<Employee>(criteriaList); 
+1

不完全確定,但是您可以在這種情況下嘗試使用'FetchMode'嗎?並嘗試使用'SELECT'而不是'JOIN'。 – SudoRahul

+0

什麼是seq_no?看起來你有重複的數據庫中的條目/聯繫人。 – kosa

+0

@Nambari這是我爲這個問題創建的一個虛擬數據。請忽略表格中的重複條目。謝謝。 – Susie

回答

3

我在Hibernate的新手,但面臨着類似的問題(父記錄被加入複製)

我已經加入FetchMode.SUBSELECT註釋(我更喜歡註解)

@OneToMany 
@Fetch(FetchMode.SUBSELECT) 

它看起來像完美的工作,我沒有重複的數據。