我正在使用hibernate JPA注释中的onetomany关系,这是我的表和实体类的详细信息......
Service (entity class: ServiceRegistration.java)
=======
serviceid
servicename
channel meta table (entity class: Channels.java)
========
channelid
channelname
service_channel (entity class: ServiceChannels.java)
===============
seq_id
serviceid
channelid
这里,service_channel表有serviceid和channelid作为forign键..我可以获取,修改记录。
但我无法删除该服务及其子记录。如果删除服务表记录,则应删除相应的service_channel表记录。这是我的实体类详细信息......
此外,我正在获取重复记录..如果服务(service1)有2个通道关联,当我获取服务列表时,我在列表中看到2个service1条目。
serviceregistration.java
@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "multichannel_service_channel", joinColumns = {
@JoinColumn(name="serviceid", unique = true)
},
inverseJoinColumns = {
@JoinColumn(name="channelid")
}
)
private Set<Channels> channelsInvolved;
@OneToMany(mappedBy="serviceRegistration")
@Cascade(org.hibernate.annotations.CascadeType.REMOVE)
private List<ServiceChannel> serviceChannels;
servicechannel.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
@Column
private int channelid;
@Column
private String channelname;
@Column
private String channeldescription;
@Column
private boolean isactive;
请帮忙解决此问题。
答案 0 :(得分:0)
你现在问2个问题。
您无法仅因为引用而删除服务。 您应该首先删除引用的实体(或更新它们以使服务不被引用)。
这意味着,您应该在删除服务之前删除相应的ServiceChannel。
通过服务“自动”删除ServiceChannel可以通过级联类型“删除孤儿”来实现,这是特定于Hibernate的功能。
对于重复列表,我认为这取决于您用于检索列表的HQL。如果您已加入/ join-fetched serviceChannels,它将导致重复的记录。您应该使用“select distinct”或添加一个不同的结果转换器来处理它。
答案 1 :(得分:0)
您是要尝试定义@ManyToMany,还是尝试使用两个@ManyToOnes模拟@ManyToMany?似乎你正在做这两件事,这是行不通的。
您有两种选择。首先,@ ManyToMany:
create table service_channel (
service_id int not null,
channel_id int not null,
primary key (service_id, channel_id));
ServiceRegistration.java
@ManyToMany
@JoinTable(name = "service_channel",
joinColumns = @JoinColumn(name="service_id"),
inverseJoinColumns = @JoinColumn(name="channel_id"))
private Set<Channel> channels;
Channel.java
@ManyToMany(mappedBy = "channels")
private Set<Service> services;
ServiceChannel.java不存在。其次,您可以将ServiceChannel提升为实体状态,并使用两个@OneToManys对整个事物进行建模:
create table service_channel (
id int not null primary key,
service_id int not null,
channel_id int not null);
ServiceChannel.java:
@ManyToOne
@JoinColumn(name = "service_id")
private Service service;
@ManyToOne
@JoinColumn(name = "channel_id")
private Channel channel;
Service.java:
@OneToMany(mappedBy = "service")
private ServiceChannel serviceChannel;
Channel.java:
@OneToMany(mappedBy = "channel")
private ServiceChannel serviceChannel;