Friday, February 6, 2009

OpenJPA one to many

One magazine may have multiple article

Unidirectional sample
Here are the annotations on magazine entity
@OneToMany(targetEntity=Article.class, 
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 Collection
articles;
In the entity of article, don't have reference to magazine.
@ElementJoinColumn is an extension in openJPA.

Bidirectional sample

Annotations in magazine
@OneToMany(mappedBy="magazine", cascade=CascadeType.PERSIST)
private Collection
articles;
mappedBy="magazine", the magazine here is the property name in Article class.

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);

List
articles = 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(Collection
articles){
this.articles = articles;

for(Article article : articles){
article.setMagazine(this);
}
}

No comments:

Post a Comment