2010-04-19 110 views
2

我有三個表。 AvailableOptions和PlanTypeRef與一個名爲AvailOptionPlanTypeAssoc的ManyToMany關聯表。修剪下來的模式看起來像這樣JPA ManyToMany參考問題

CREATE TABLE [dbo].[AvailableOptions](
    [SourceApplication] [char](8) NOT NULL, 
    [OptionId] [int] IDENTITY(1,1) NOT NULL, 
    ... 
) 

CREATE TABLE [dbo].[AvailOptionPlanTypeAssoc](
    [SourceApplication] [char](8) NOT NULL, 
    [OptionId] [int] NOT NULL, 
    [PlanTypeCd] [char](2) NOT NULL, 
) 

CREATE TABLE [dbo].[PlanTypeRef](
    [PlanTypeCd] [char](2) NOT NULL, 
    [PlanTypeDesc] [varchar](32) NOT NULL, 
) 

而Java代碼看起來像這樣。

//AvailableOption.java 
@ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER) 
@JoinTable(
    name = "AvailOptionPlanTypeAssoc", 
    joinColumns = { @JoinColumn(name = "OptionId"), 
        @JoinColumn(name="SourceApplication")}, 
    [email protected](name="PlanTypeCd")) 
List<PlanType> planTypes = new ArrayList<PlanType>(); 

//PlanType.java 
@ManyToMany 
@JoinTable(
    name = "AvailOptionPlanTypeAssoc", 
    joinColumns = { @JoinColumn(name = "PlanTypeCd")}, 
    inverseJoinColumns={@JoinColumn(name="OptionId"), 
         @JoinColumn(name="SourceApplication")}) 
List<AvailableOption> options = new ArrayList<AvailableOption>(); 

問題出現在進行選擇後,它將自己加入到AvailableOptions中。請注意以下回溯的SQL代碼。第二個內部聯接應該在PlanTypeRef上。

SELECT t0.OptionId, 
    t0.SourceApplication, 
    t2.PlanTypeCd, 
    t2.EffectiveDate, 
    t2.PlanTypeDesc, 
    t2.SysLstTrxDtm, 
    t2.SysLstUpdtUserId, 
    t2.TermDate 
FROM dbo.AvailableOptions t0 
    INNER JOIN dbo.AvailOptionPlanTypeAssoc t1 
    ON t0.OptionId = t1.OptionId AND t0.SourceApplication = t1.SourceApplication 
    INNER JOIN dbo.AvailableOptions t2 
    ON t1.PlanTypeCd = t2.PlanTypeCd 
WHERE (t0.SourceApplication = ? AND t0.OptionType = ?) 
ORDER BY t0.OptionId ASC, t0.SourceApplication ASC 
[params=(String) testApp, (String) junit0]} 

回答

3

您正在映射雙向關聯。這意味着你必須選擇一方作爲協會的所有者。這一方將負責更新數據庫中的關係。

如果您選擇AvailableOption作爲關係的所有者,並且您想爲其創建新的PlanType,則必須將該種類添加到該選項。僅將該選項添加到種植類型將不起作用。

這裏是映射:

//AvailableOption.java 
@ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER) 
@JoinTable(
    name = "AvailOptionPlanTypeAssoc", 
    joinColumns = { @JoinColumn(name = "OptionId"), 
        @JoinColumn(name="SourceApplication")}, 
    [email protected](name="PlanTypeCd")) 
List<PlanType> planTypes = new ArrayList<PlanType>(); 

//PlanType.java 
@ManyToMany(
    mappedBy = "planTypes" 
) 
List<AvailableOption> options = new ArrayList<AvailableOption>(); 

您也可以參考hibernate annotation documentation chapter 2.2.5

問候 大衛