JPA ManyToMany引用问题

时间:2010-04-19 15:01:08

标签: java sql orm jpa openjpa

我有三张桌子。 AvailableOptions和PlanTypeRef,带有名为AvailOptionPlanTypeAssoc的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")},
  inverseJoinColumns=@JoinColumn(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]}

1 个答案:

答案 0 :(得分:3)

您正在映射双向关联。这意味着您必须选择一方作为关联的所有者。这方将负责更新数据库中的关系。

如果您选择AvailableOption作为关系的所有者,并且您想要一个新的PlanType,则必须将该植物类型添加到该选项中。仅将选项添加到植物类型将不起作用。

这是映射:

//AvailableOption.java
@ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinTable(
  name = "AvailOptionPlanTypeAssoc",
  joinColumns = { @JoinColumn(name = "OptionId"),
                  @JoinColumn(name="SourceApplication")},
  inverseJoinColumns=@JoinColumn(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

此致 大卫