2017-07-07 217 views
0

我有兩個關係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); 
} 

回答

0

你是做觀衆救人第一,但在你的代碼中定義的關係:

事件將處理觀衆的持續存在,由於此:

@ManyToMany(
      fetch = FetchType.LAZY, 
      targetEntity = Audience.class, 
      cascade = {CascadeType.PERSIST, CascadeType.MERGE}) 

所以您首先創建觀衆,然後創建事件,然後將觀衆列表附加到事件並將事件對象保存到數據庫中。

+0

你的意思是,如果我會評論「audienceRepository.save(觀衆)」,然後保存「事件」會保存我的觀衆?我忽略了「audienceRepository.save(觀衆)」,它看起來像事件沒有保存它,因爲當我「查找所有」觀衆時,什麼都沒有。 – Evgenii

+0

你是通過事件對象找到觀衆還是直接找到觀衆? –

+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; 
    } 
} 

約多對多關聯的更多信息和「公用事業法」:Hibernate User Guide

exampletests

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; 
} 

而且我有兩個庫的保存觀衆和延伸的彈簧的JpaRepository活動。

現在我可以這樣創建對象:

audienceRepository.save(new Audience("Name")); 

,並將其添加到我的事件是這樣的:

Event eventFirst = new Event(); 
eventFirst.getAudiences().add(audiences.get(0)); 
eventRepository.save(eventFirst);