在JPA中,我有2个实体:Entry和Comment。条目包含两个Comment对象集合。
@Entity public class Entry { ... @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @IndexColumn(base = 1, name = "dnr") private List<Comment> descriptionComments = new ArrayList<Comment>(); @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @IndexColumn(base = 1, name = "pmnr") private List<Comment> postMortemComments = new ArrayList<Comment>(); ... }
为了存储此类对象,JPA + Hibernate创建“ Entry”表,“ Comment”表和单个“ Entry_Comment”:
create table Entry_Comment (Entry_id integer not null, postMortemComments_id integer not null, pmnr integer not null, descriptionComments_id integer not null, dnr integer not null, primary key (Entry_id, dnr), unique (descriptionComments_id), unique (postMortemComments_id))
对象的存储失败,descriptionComments_id并且postMortemComments_id不能同时为“非null”。
descriptionComments_id
postMortemComments_id
如何使用JPA + Hibernate存储包含两个相同类型的集合的对象?
这是许多Hibernate错误(准确地说是HHH-3410)之一。
我设法通过@JoinTable在@OneToMany关系中添加注释来解决它,每个注释都有自己的表名。
@JoinTable
@OneToMany
在您的情况下,它看起来像这样:
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(name="entity_descriptioncomments") @IndexColumn(base = 1, name = "dnr") private List<Comment> descriptionComments = new ArrayList<Comment>(); @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(name="entity_postmortemcomments") @IndexColumn(base = 1, name = "pmnr") private List<Comment> postMortemComments = new ArrayList<Comment>();
注意 :您还必须添加@IndexColumn注释(由于多个EAGER包的另一个Hibernate问题:HHH-1718 / EJB-346)。
@IndexColumn