Reputation: 1328
I have two tables: writers: writer_id(pk, auto increment), writer_name(varchar) articles: article_id(pk,auto increment), article_name(varchar),writer_id(fk,int)
one writer can have more than one article. so mapping from articles to writers is many to one.
here is my model for articles:
@Entity
@Table(name = "articles")
public class Article {
@Id
@GeneratedValue
@Column(name = "article_id")
private Long articleId;
@Column(name = "article_name", nullable = false, length=20)
private String articleName;
private Writer writer;
public Writer getWriter() {
return writer;
}
public void setWriter(Writer writer) {
this.writer = writer;
}
//rest of setters and getters
}
What will be annotations for writer property?
Heres my controller class:
public class ArticleController {
@Autowired
private ArticleService articleService;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addArticle(@ModelAttribute("article") Article article,BindingResult result) {
return new ModelAndView("addArticle");
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveArticle(@ModelAttribute("article") Article article,BindingResult result) {
articleService.addArticle(article);
return new ModelAndView("redirect:/articles/list");
}
}
In my addArticle.jsp page, i have populated writers in a select box (which has value of writer_id and label of writer_name).
Please advice me.
Upvotes: 1
Views: 1967
Reputation: 47290
Here is one option, others are available :
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "writer_fk", nullable = false)
private Writer writer;
And in writer you can have
@OneToMany(mappedBy = "writer")
private Set<Article> articles= new HashSet<Article>();
Upvotes: 1