我有两个关系ManyToMany的类,我想创建Audiences,然后将它们添加到事件中,但它会抛出“分离”异常。
class Event {
@ManyToMany(
fetch = FetchType.LAZY,
targetEntity = Audience.class,
cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "UC_EVENT_AUDIENCE",
joinColumns = @JoinColumn(name = "event_id"),
inverseJoinColumns = @JoinColumn(name = "audience_id"))
private List<Audience> targetAudiences = new ArrayList<>();
}
clsas Audience {
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "targetAudiences")
private List<Event> events = new ArrayList<>();
}
public void run(ApplicationArguments args) throws Exception {
//Generate audience data
List<Audience> audiences = dataGenerator.createAudiences();
//Save to db
audienceRepository.save(audiences);
Event event = new Event();
event.setTargetAudiences(audiences);
eventRepository.save(events);
}
答案 0 :(得分:0)
您正在首先保存受众群体,但是在您的代码中定义了关系:
活动将因此而处理受众的持久性:
@ManyToMany(
fetch = FetchType.LAZY,
targetEntity = Audience.class,
cascade = {CascadeType.PERSIST, CascadeType.MERGE})
首先创建受众,然后创建事件,然后将受众列表附加到事件,并将事件对象最终保存到数据库。
答案 1 :(得分:0)
作为一种变体,您可以使用这种'PrePersist'util方法来“链接”事件和受众:
@Entity
public class Event {
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private final Set<Audience> audiences = new HashSet<>();
@PrePersist
public void addAudiences() {
audiences.forEach(audience -> audience.getEvents().add(this));
}
}
@Entity
public class Audience {
@ManyToMany(mappedBy = "audiences")
private final Set<Event> events = new HashSet<>();
//...
public Set<Event> getEvents() {
return events;
}
}
有关ManyToMany关联和'实用工具方法'的更多信息:Hibernate User Guide
答案 2 :(得分:0)
我这样做了,它为我工作:
public class Event {
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "event_audience",
joinColumns = @JoinColumn(name = "event_id"),
inverseJoinColumns = @JoinColumn(name = "audience_id"),
uniqueConstraints = @UniqueConstraint(columnNames = {"event_id", "audience_id"}))
private List<Audience> audiences = new ArrayList<>();
}
public class Audience {
@Column(name = "audience_name", nullable = false, unique = true)
private String name;
}
此外,我还有两个用于保存Audience和Events的存储库,用于扩展spring的JpaRepository。
现在我可以像这样创建受众:
audienceRepository.save(new Audience("Name"));
并将它们添加到我的活动中:
Event eventFirst = new Event();
eventFirst.getAudiences().add(audiences.get(0));
eventRepository.save(eventFirst);