Unidirectional sample
Here are the annotations on magazine entity
@OneToMany(targetEntity=Article.class,In the entity of article, don't have reference to magazine.
cascade = { CascadeType.PERSIST, CascadeType.REFRESH },
fetch = FetchType.EAGER) //mappedBy="magazine",
@ElementJoinColumn(name = "MAGAZINE_ID", referencedColumnName = "ID")
// the name is the column name in the article table
@OrderBy
private Collectionarticles;
@ElementJoinColumn is an extension in openJPA.
Bidirectional sample
Annotations in magazine
@OneToMany(mappedBy="magazine", cascade=CascadeType.PERSIST)mappedBy="magazine", the magazine here is the property name in Article class.
private Collectionarticles;
Annotations in Article
@ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST)
@Column(name = "MAG_ID")
private Magazine magazine;
When persist magazine with a list of articles, you need set magazine into each article explicitly. It is not needed if it is unidirectional.
Here is the sample code
Magazine magazine = new Magazine();
magazine.setCoverArticle(article1);
magazine.setIsbn("isbn00000000009");
magazine.setTitle("ELLE");
magazine.setPrice(25.00);
Listarticles = new ArrayList ();
article2.setMagazine(magazine); //1*
article3.setMagazine(magazine); //2*
articles.add(article2);
articles.add(article3);
magazine.setArticles(articles);
magazineDao.persistMagazine(magazine);
1* and 2* could also be done in setArticles() of the Magazine entity class.
public void setArticles(Collectionarticles){
this.articles = articles;
for(Article article : articles){
article.setMagazine(this);
}
}
No comments:
Post a Comment