我有兩個關係ManyToMany類,我想創建觀衆,然後將它們添加到事件,但它拋出「分離」異常。休眠ManyToMany保存
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);
}
你的意思是,如果我會評論「audienceRepository.save(觀衆)」,然後保存「事件」會保存我的觀衆?我忽略了「audienceRepository.save(觀衆)」,它看起來像事件沒有保存它,因爲當我「查找所有」觀衆時,什麼都沒有。 – Evgenii
你是通過事件對象找到觀衆還是直接找到觀衆? –
您還必須在保存活動之前爲觀衆設置活動。因爲它的雙向關係 –