在spring mvc 3和hibernate中进行多对一映射

时间:2012-04-19 13:23:46

标签: hibernate spring-mvc

我有两张桌子: writer:writer_id(pk,auto increment),writer_name(varchar) 文章:article_id(pk,自动增量),article_name(varchar),writer_id(fk,int)

一位作家可以有多篇文章。所以从文章到作家的映射是多对一的。

这是我的文章模型:

@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
}

作家财产的注释是什么?

继承我的控制器类:

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

在我的addArticle.jsp页面中,我在一个选择框中填充了编写器(其值为writer_id,编号为writer_name)。

请建议我。

1 个答案:

答案 0 :(得分:1)

这是一个选项,其他选项可用:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "writer_fk", nullable = false)
private Writer writer;

在作家中你可以拥有

@OneToMany(mappedBy = "writer")
private Set<Article> articles= new HashSet<Article>();