【问题标题】:Many to one mapping in spring mvc 3 and hibernatespring mvc 3和hibernate中的多对一映射
【发布时间】:2012-04-19 13:23:45
【问题描述】:

我有两张桌子: writers: writer_id(pk, auto increment), writer_name(varchar) 文章:article_id(pk,auto increment), 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
}

writer 属性的注释是什么?

这是我的控制器类:

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

请给我建议。

【问题讨论】:

    标签: hibernate spring-mvc


    【解决方案1】:

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

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

    在 writer 中你可以拥有

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

    【讨论】:

    • 谢谢,但是在 saveArticle 方法中,我必须设置 article.setWriter(writer) 还是绑定到文章(模态属性)?
    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多