2012-06-07 101 views
0

我有两个实体:EJB 3持久性

语料库实体:

@Entity(name = "CORPUS") 
public class Corpus implements Serializable { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "ID") 
    private Long id; 

    @OneToMany(mappedBy = "corpus", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 
    private Collection<CorpusHistory> corpusHistories; 

    //Setters and getters... 
} 

语料库历史实体:

@Entity(name = "CORPUS_HISTORY") 
public class CorpusHistory implements Serializable { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "ID") 
    private Long id; 

    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name="CORPUS_ID") 
    private Corpus corpus; 

    //Setters and getters... 
} 

语料库实体可以有文集许多历史记录所以我用@OneToMany注释它。我希望使用语料库标识完成映射,因此我正在使用语料库历史记录实体中的@JoinColumn(name="CORPUS_ID")@ManyToOne注释。

坚持语料对象数据库之前我胼病史采集设置它:

LinkedList<CorpusHistory> corpusHistories = new LinkedList<CorpusHistory>(); 
for (Change change : changes) { 
    CorpusHistory corpusHistory = new CorpusHistory(); 
    //corpusHistory.setCorpusId(String.valueOf(corpusId)); ????? 
    corpusHistory.setRevisionAuthor(change.getName()); 
    corpusHistory.setRevisionDate(change.getWhen()); 
    corpusHistory.setRevisionNote(change.getNote()); 
    //corpusHistoryFacade.create(corpusHistory); 
    corpusHistories.add(corpusHistory); 
} 

corpus.setCorpusHistories(corpusHistories); 

记录被创造的一切是确定,但在语料库历史表中的列CORPUS_ID始终为空。当我从数据库检索语料库时,历史列表是空的。我不明白如果语料库记录尚未创建,我怎么能指定语料库ID到语料库历史?

这不是EJB工作要做的吗?使用@OneToMany@ManyToOne映射,适当的ID应映射并存储到适当的列中(在这种情况下,语料库ID应存储在语料库历史记录列CORPUS_ID的每个记录中)。

或者我在这里误解了一些东西?我已经尝试过很多教程,但没有成功......我被困在这里。

回答

1
for (Change change : changes) { 
    CorpusHistory corpusHistory = new CorpusHistory(); 
    corpusHistory.setCorpus(corpus); 
    ... 
} 

所有者方是没有mappedBy属性的一方。您必须初始化所有者端,以告知JPA该关联存在。由于您在corpus.histories上进行了级联,因此当您坚持使用语料库时,JPA还会保留历史记录。

+0

是的,你是对的,我花了整整一天的时间...现在一切都像魅力:)谢谢。 –