2011-10-06 62 views
0

我有以下實體和我已經刪除了的ServiceRegistration和ServiceChannels條目,當我刪除的ServiceRegistration記錄。但是現在,如果我在服務註冊中刪除一條記錄,它將刪除元數據表中的記錄。Spring MVC的3 Hibernate的JPA批註一對多和多對一的關係級聯刪除

ServiceRegistration.Java

@OneToMany(cascade=CascadeType.ALL,fetch = FetchType.EAGER) 
@JoinTable(name = "ServiceChannel", joinColumns = { 
@JoinColumn(name="serviceid", unique = true) 
}, 
inverseJoinColumns = { 
@JoinColumn(name="channelid") 
} 
) 

private List<Channels> channelsInvolved; 

    public List<Channels> getChannelsInvolved() { 
    return channelsInvolved; 
    } 

public void setChannelsInvolved(List<Channels> channelsInvolved) { 
    this.channelsInvolved = channelsInvolved; 
    } 

ServiceChannels.java

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column private int servicechannelid;  

@ManyToOne 
@JoinColumn(name = "serviceid") 
private ServiceRegistration serviceRegistration; 

@ManyToOne 
@JoinColumn(name = "channelid") 
private Channels channels; 

Channels.java >>包含元數據

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column private int channelid; 
@Column private String channelname; 

@Override 
    public boolean equals(final Object obj) { 
     if (obj instanceof Channels) { 
      final Channels other = (Channels) obj; 
      if (other.getChannelid() == getChannelid()) { 
       return true; 
      } 
     } 
     return false; 
    } 

請幫助我如何做級聯刪除這實體關係。

回答

0

首先,如果你不想讓刪除一個ServiceRegistration時刪除的頻道,你應該做的:

@OneToMany(fetch = FetchType.EAGER) 
@JoinTable(name = "ServiceChannel", joinColumns = { 
@JoinColumn(name="serviceid", unique = true) 
}, 
inverseJoinColumns = { 
@JoinColumn(name="channelid") 
} 
) 

private List<Channels> channelsInvolved; 

在服務註冊(禁用級聯)。

另外,如果你想,當你刪除一個ServiceRegistration你ServiceChannel刪除,您必須配置在側面的ServiceRegistration的關係:

@OneToMany(mappedBy="serviceRegistration", cascade=CascadeType.REMOVE) // Edited to specify the owning side of the relationship 
private List<ServiceChannel> serviceChannels; 
+0

我得到這個error..Foreign鍵(FK47A18582B04FBB38:mcp_service_mcp_servicechannel [serviceChannels_servicechannelid]))必須具有相同數目的所引用的主鍵列(mcp_servicechannel [服務ID,的channelID]) – Surez

+0

我編輯的答案補充的關係(的mappedBy屬性)的持有端。這在OneToMany關係中是必需的。 –

+0

我按照你所說的做了更改,當我刪除任何沒有任何服務通道的服務註冊時,它工作正常。但是,如果我有任何服務註冊的任何服務通道,它的拋出'不能刪除記錄!!!批量更新返回意外的行數....「。我看到由休眠生成的查詢爲 Hibernate:從mcp_servicechannel刪除其中serviceid =? 休眠:從mcp_servicechannel中刪除servicechannelid =? – Surez