2010-08-09 71 views
0

我在建模JPA中的以下問題時遇到問題。我有一個JPA實體類 '用戶',像這樣: (訪問器/轉變器/外來場/外來JPA配置爲簡潔起見省略)JPA映射問題 - 請求的建模方向


    @Entity 
    class User { 
     @Id 
     @Generated Value 
     long id; 
     @OneToMany 
     Report contributorReports; // All the reports where this user is contributor 
     @OneToMany ownerReports; // All the reports where this user is owner 
     String username; 
    } 

和JPA實體類 '報告'


@Entity 
class Report { 
    @Id 
    @GeneratedValue 
    long id; 
    @OneToOne 
    User contributor; 
    @OneToOne 
    User owner; 
    SomeData data; 
} 

我想模擬這樣的關係:

  • 報告必須包含一個貢獻者和所有者
  • 我CA N接入所有報表的用戶一直是「貢獻者」爲通過用戶實體
  • 我可以訪問所有報表的用戶已經「擁有者」爲通過用戶實體

我想象的我將結束了,看上去隱約像這樣的映射表:


CREATE TABLE user_report { 
    BIGINT reportId, 
    BIGINT contributorId, 
    BIGINT ownerId, 
} 

我試圖解決類似問題:


    @OneToOne 
    @JoinTable(name = "user_report", 
      joinColumns = { 
        @JoinColumn(name = "reportOwner_ID", referencedColumnName = "ID")} 
      ) 
    private User owner; 
    @OneToOne 
    @JoinTable(name = "user_report", 
      joinColumns = { 
       @JoinColumn(name = "reportContributor_ID", referencedColumnName = "ID")} 
      ) 
    private User contributor; 

這會產生像表:

 
CREATE TABLE user_report (
    BIGINT ownerReport_ID, // Report ID 
    BIGINT reportOwner_ID, // UserID owner 
    BIGINT contributorReport_ID, // Report ID 
    BIGINT reportContributor_ID // UserID contributor 
) 

所以當JPA試圖映射到這個表中,每個字段分別映射和,因爲只有該行的一半被提交失敗,拋出此異常:

Caused by: java.sql.BatchUpdateException: Field 'ownerReport_ID' doesn't have a default value

我希望能夠就如何最好地模擬我所設想的關係得到一些指導。 (或者更好的方式來設想這種關係)如果需要額外的信息,我會很樂意提供。

親切的問候 馬特

+0

爲什麼你在報告端使用'@ OneToOne',它應該是'@ ManyToOne'。 – axtavt 2010-08-09 15:41:54

回答

2

根據您的要求,我相信你做到這一點,2 1:從用戶M與匹配M至報告:1回各。

@Entity 
class User { 
    @Id 
    @Generated Value 
    long id; 

    // All the reports where this user is contributor 
    @OneToMany(mappedBy="contributor") 
    List<Report> contributorReports; 

    // All the reports where this user is owner 
    @OneToMany(mappedBy="owner") 
    List<Report> ownerReports; 

    String username; 
} 

則您的報告類會是什麼樣子:

@Entity 
class Report { 
    @Id 
    @GeneratedValue 
    long id; 

    @ManyToOne 
    User contributor; 

    @ManyToOne 
    User owner; 

    SomeData data; 
} 

這種情況也有可能與連接表,但不要求根據您的要求,因爲我理解他們。

Doug

+0

感謝道格,那確實正是我所需要的!樹林和所有的森林。 – Matt 2010-08-09 17:38:29