1

我有两个表: 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)。

请给我建议。

4

1 回答 1

1

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

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

在作家中,您可以拥有

@OneToMany(mappedBy = "writer")
private Set<Article> articles= new HashSet<Article>();
于 2012-04-19T13:30:10.567 回答