2016-02-24 61 views
0

我在使用多個主鍵創建聯接表時遇到問題。下面是我的表結構:使用多個主鍵創建聯結表?

Table Structure

下面是我的JPA實現:

@Entity 
@Table(name = "label") 
public class Label { 
    @Id 
    @Column(name = "tenant_id") 
    private String tenant_id; 

    @Id 
    @Column(name = "label_id") 
    private String label_id; 

    @JsonIgnore 
    @ManyToMany(targetEntity = Report.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) 
    @JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "label_id"), inverseJoinColumns = @JoinColumn(name = "report_id")) 
    private Set<Report> reports; 
} 

@Entity 
@Table(name = "report") 
public class Report { 
    @Id 
    @Column(name = "tenant_id") 
    private String tenant_id; 

    @Id 
    @Column(name = "report_id") 
    private String report_id; 

    @column(name = "created_by") 
    private String created_by; 

    @JsonIgnore 
    @ManyToMany(targetEntity = Label.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) 
    @JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "report_id"), inverseJoinColumns = @JoinColumn(name = "label_id")) 
    private Set<Label> labels; 

} 

這工作得很好,但是當我嘗試在tenant_id添加到組合,像這樣:

Label.java編輯:

@JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "label_id"), inverseJoinColumns = { @JoinColumn(name = "report_id"), @JoinColumn(name = "tenant_id") }) 
private Set<Report> reports; 

Report.java編輯:

@JoinTable(name = "tagging", joinColumns = @JoinColumn(name = "report_id"), inverseJoinColumns = { @JoinColumn(name = "label_id"), @JoinColumn(name = "tenant_id") }) 
private Set<Label> labels; 

我收到一個錯誤,說「A Foreign key refering has the wrong number of column. should be 1」。據我所知,這是因爲我只有一個名爲Report的主鍵並標記每個主鍵,因此我無法將tenant_id映射爲JoinColumn。不過,我想知道,有沒有什麼辦法可以設置tenant_id的時候report_idlabel_id也被設置?任何幫助,將不勝感激。謝謝!

編輯:實體中的@Id字段在報告和標籤類中都是tenant_id和id。

+0

你的外鍵是什麼?只是所以我可以嘗試爲你寫一個映射 – Desorder

+0

@Desorder我其實沒有外鍵。我的表沒有任何外鍵。 – user1871869

+0

tenant_id爲什麼不是其他兩張表中PK的一部分?爲什麼在連接表中有2個字符串是字符串,但在其他2個表中卻有int?首先修復表格 –

回答

0

對不起,我無法嘗試,但從我的頭頂,這是這樣的。有幾件事情需要像完整的註釋屬性一樣解決,因爲列名和類成員不一樣,但這就是想法。 :)

更多信息here

報告類

@Entity 
public class Report { 

    @Id 
    private Integer id; 

    @Column 
    private String createdBy; 

    @Column 
    private String tenantId; 

    @OneToMany 
    private List<Tagging> taggings = new ArrayList<>(); 

    // getter and setters 

} 

Label類

@Entity 
public class Label { 

    @Id 
    private Integer id; 

    @Column 
    private String tenantId; 

    @OneToMany 
    private List<Tagging> taggings = new ArrayList<>(); 

    // getter and setters 

} 

標註類

@Entity 
public class Tagging { 

    @EmbeddedId 
    private TaggingId id; 

    @OneToMany 
    private Report report; 

    @OneToMany 
    private Label label; 

    // getter and setters 

} 

@Embeddable 
class TaggingId { 

    private Integer reportId; 

    private String labelId; 

    private String tenantId; 

    // getter and setters 

}