2017-04-04 109 views
1

我想構建一個應用程序,它將接收帶有員工列表的XML文件並將父子/員工管理者關係存儲在單個數據庫表中。親子關係 - 自我加入映射

我的XML文件看起來像這樣的:

<Employees> 
    <Employee manager="Patrick">Martin</Employee> 
    <Employee manager="Patrick">Kent</Employee> 
    <Employee manager="Martin">Mark</Employee> 
    <Employee>Hugo</Employee> <!-- root element of the employee-manager tree --> 
    <Employee manager="Hugo">Osa</Employee> 
    <Employee manager="Osa">Patrick</Employee> 
</Employee> 

一個員工只能有一個經理,而是一個經理可以有多個下屬/員工。

我解開收到的XML文件時沒有麻煩,但現在我試圖創建合適的模型,這將允許我將未編組的值存儲在數據庫中。數據應該存儲在一個名爲「僱員」表,並應包含以下數據:

------------------------------ 
| id   | Integer | 
------------------------------ 
| employee_name | String  | 
------------------------------ 
| parent_id  | Integer | -- reference to the manager 
------------------------------ 

我創建了一個名爲Employee新的類,但我不知道如何定義適當的多對一/一對多註釋。

因爲我對此很新,我已經谷歌搜索了幾個例子和教程(以及對堆棧溢出的類似問題的答案),但我想我在這個上犯了一個大錯誤定義這個模型時的實現。我最新的嘗試是這樣的:

public class Employee { 
    @Id 
    @GeneratedValue 
    private int id; 

    @Column(name = "parent_id") 
    @Transient 
    @ManyToOne(cascade={CascadeType.ALL}) 
    private String managerName; 

    @Column(name = "employee_name") 
    @JoinColumn(name="parent_id") 
    private String employeeName; 

    // getters and setters 

如果任何人都可以在定義適當的模型的方向指向我,那將是非常非常感謝!

回答

1

Hibernate當你想映射ManyToOne關係,你的實體,而不僅僅是性能之間的映射,所以你需要引用Employee類型的對象並不僅Stringid

問題:

  • 所以,你的映射是不正確的,會引發許多映射錯誤, 而不是寫:

    @Column(name = "parent_id") 
    @Transient 
    @ManyToOne(cascade={CascadeType.ALL}) 
    private String managerName; 
    

    您需要映射ManyToOne realtionship這樣的:

    @ManyToOne(cascade={CascadeType.ALL}) 
    @JoinColumn(name="manager_id") 
    private Employee manager; 
    
  • 並確保您映射這樣的關係的另一面:

    @OneToMany(mappedBy="manager") 
    private Set<Employee> subordinates = new HashSet<Employee>(); 
    
  • 而且你映射employee_name是不正確的列,則 @JoinColumn僅用於關係,不能以使用 簡單列,你需要把它寫這樣的:

    @Column(name = "employee_name") 
    private String employeeName; 
    
  • @Transient是在映射沒用,我們只使用它,如果我們 想使用attribut e不會保留在數據庫中。

  • 而且最重要確保您@Entity映射類,因此它可以 堅持在數據庫中。

例子:

您可以檢查Hibernate Self Join Annotations One To Many mapping example它使用要實現相同的模型。

+0

謝謝,chsdk。我會盡力按照您提出的方式實施解決方案。希望我能做到。 – hezus

+0

@hezus不客氣,我相信它會給你預期的結果。 –

-1

您應該簡單地有多對一關係到你的Employee表,也就是幾名員工可以有相同的經理(誰也是僱員)和經理這一領域仍將是空的,就像這樣:

@Entity 
@Table(name = "EMPLOYEE") 
public class Employee { 

    @Id 
    @GeneratedValue 
    private int id; 

    @ManyToOne 
    private Employee manager; 

    @Column(name = "employee_name") 
    private String employeeName;