通过了解hibernate如何映射集合bidiractional,我有一点问题。
通缉如下: 表模式:
事件(e_id,date,i_id)
info(i_id,detailDesc)
我有多个事件和一些信息对象,它们将详细信息汇总到x事件。作为对象,我有不同的事件对象和一些应该包含事件对象列表的Info对象。与Info Object相关的Event Objects应该有一个相关的info对象,请参阅下面的类信息。
@Entity
@Table(name = "info")
public class Info {
@Id
@GenericGenerator(name = "gen", strategy = "increment")
@GeneratedValue(generator = "gen")
@Column(name = "i_id")
private long id;
@JoinTable(name = "events",
joinColumns = @JoinColumn(name = "e_id"),
inverseJoinColumns = @JoinColumn(name = "i_id"))
@OneToMany(targetEntity = Event.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Event> events;
String detailDesc;
}
@Entity
@Table(name = "event")
public class Event {
@Id
@GenericGenerator(name = "gen", strategy = "increment")
@GeneratedValue(generator = "gen")
@Column(name = "e_id")
private long id;
// Can be NULL
@ManyToOne(targetEntity = Info.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL, optional = true)
@JoinColumn(name = "i_id")
private Info info;
private Date date;
}
就像现在一样,hibernate表示重复条目或外键约束失败(event
,CONSTRAINT FK_r9sdjn6nelyo5be86vu0b2prs
FOREIGN KEY(e_id
)参考info
({{1} }))
答案 0 :(得分:1)
您的映射不正确。鉴于您的架构,您没有使用JoinTable,因此在@ManyToOne侧设置@JoinColumn(就像您所拥有的那样)并简单地使用&#39; mappedBy&#39;相反的。确保关系的两侧都设置为确保级联按预期工作。
如果您确实想要使用连接表(而不是事件&gt;信息中的FK),那么您可以将现有的@JoinTable移动到@ManyToOne并删除@JoinColumn。无论您使用的是@JoinTable还是@JoinColumn,反面都将保持如下。
@Entity
@Table(name = "info")
public class Info {
@Id
@GenericGenerator(name = "gen", strategy = "increment")
@GeneratedValue(generator = "gen")
@Column(name = "i_id")
private long id;
@OneToMany(mappedBy="info" cascade = CascadeType.ALL)
private List<Event> events;
String detailDesc;
//set both sides of the relationship
public void addEvent(Event event){
event.setInfo(this);
events.add(event);
}
public List<Event> getEvents(){
//return unmodifiable list or iterator to force clients through addEvent() method
}
}
@Entity
@Table(name = "event")
public class Event {
@Id
@GenericGenerator(name = "gen", strategy = "increment")
@GeneratedValue(generator = "gen")
@Column(name = "e_id")
private long id;
@ManyToOne(cascade = CascadeType.ALL, optional = true)
@JoinColumn(name = "i_id")
private Info info;
private Date date;
}