I have two entities:
Corpus entity:
@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...
}
Corpus history entity:
@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...
}
The corpus entity can have many records of corpus history so I am annotating it with @OneToMany. I want the mapping to be done using the corpus id so I am using @JoinColumn(name="CORPUS_ID") and @ManyToOne annotation in corpus history entity.
Before persisting the corpus object to database I set the corpus history collection to it:
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);
Records are created all it is ok but in the corpus history table the CORPUS_ID column is always null. And when I am retrieving corpus from database the history list is empty. I do not understand how can I specify the corpus id to corpus history if the corpus record is not created yet?
Isn’t this an EJB job to do? With @OneToMany and @ManyToOne mapping the appropriate ID’s should be mapped and stored into appropriate columns (in this case the corpus id should be stored in every record of corpus history column CORPUS_ID).
Or I am misunderstanding something here? I have tried many tutorials, no success… I am stuck here.
The owner side is the one without the mappedBy attribute. You must initialize the owner side in order to tell JPA that the association exists. Since you have a cascade on corpus.histories, when you persist the corpus, JPA will also persist the histories.