2011-10-06 61 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