2017-04-17 119 views
0

我試圖將下表映射到實體。帶3個外鍵的休眠表

Involved Tables 的事件表的映射是這樣的:

@Id 
@Column(name = "id") 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
private Integer _id; 
@Column(name = "title") 
private String _title; 
@Column(name = "description") 
private String _description; 
@Column(name = "location") 
private String _place; 
@Column(name = "start") 
private Date _start; 
@Column(name = "end") 
private Date _stop; 
@Column(name = "points") 
private int _points; 
@Enumerated(EnumType.STRING) 
@Column(name = "type") 
private EventType _eventtype; 

@ManyToMany(fetch = FetchType.EAGER) 
@JoinTable(name = "event2work2instrumentation", joinColumns = { 
     @JoinColumn(name = "event")}, 
     inverseJoinColumns = {@JoinColumn(name = "work")}) 
private Set<WorkMapper> _works = new HashSet<>(0); 

@ManyToMany(fetch = FetchType.EAGER) 
@JoinTable(name = "event2work2instrumentation", joinColumns = { 
     @JoinColumn(name = "event")}, 
     inverseJoinColumns = {@JoinColumn(name = "instrumentation")}) 
private Set<InstrumentationMapper> _instrumentations = new HashSet<>(0); 

它工作正常,我從數據庫中獲取的所有數據,但是當我嘗試存儲具有工作的新事件,分配給它的工具我得到錯誤。

當event2work2instrumentation表中的字段配置爲不爲空時,我得到:字段沒有默認值。

如果我給外地的默認值,我得到:

SQLIntegrityConstraintViolationException: Cannot add or update a child row: 
    a foreign key constraint fails (`schema`.`event2work2instrumentation`, CONSTRAINT `e2w2i_instrumentation_fk` FOREIGN KEY (`instrumentation`) REFERENCES `instrumentation` (`id`)) 

你有什麼想法?它可能取決於儀器和/或工作的映射嗎?這些類在其映射中沒有對event2work2指令的引用。

+0

我不是專家,但你可能需要向'@ManyToMany()'添加'cascade = CascadeType.INSERT'或'cascade = CascadeType.ALL'。 – qtips

回答

0

的解決方案是使用地圖和MapKeyJoinColumn註釋:

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 
@JoinTable(name = "event2work2instrumentation", joinColumns = { 
     @JoinColumn(name = "event")}, 
     inverseJoinColumns = {@JoinColumn(name = "instrumentation")}) 
@MapKeyJoinColumn(name = "work") 
private Map<WorkMapper, InstrumentationMapper> _eventToWorkAndInstrumentationMappers = new HashMap<>(); 
0

嘗試截斷兩個表,然後存儲新的FK。它發生在我身上時,我有一個object_related_id這是不是在對象表作爲一個id