私は彼のページに移動し、そこからフォームを持っているページに移動し、ユーザーを登録することができます2つのエンティティユーザ及び条多対1。あるオブジェクトを別のオブジェクトに関連付ける方法は?
ユーザー
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
@Column(name="user_id")
private Integer id;
@Column(name="name")
private String name;
@OneToMany(mappedBy = "userId")
private List<Article> articles;
条
@Entity
@Table(name = "article")
public class Article {
@Id
@GeneratedValue
private Integer articleId;
private String name;
@ManyToOne
@JoinColumn(name = "user_id")
private User userId;
を持っています記事を提出する。
<form:form method="POST" modelAttribute="article"
action="${pageContext.request.contextPath}/addArticle">
<table>
<tbody>
<tr>
<td>Title:</td>
<td><form:input path="name"></form:input></td>
</tr>
<tr>
<td>Author id:</td>
<td><form:input path="userId"></form:input></td>
</tr>
<%-- <form:input type="text" path="userId" disabled="true"/> --%>
<%-- <form:input type="hidden" path="id" id="id"/> --%>
<tr>
<td><input value="Add" type="submit"></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
問題は、そのユーザーと記事を関連付ける方法がわかりません。今の私のArticleControllerはは
@Controller
public class ArticleController {
@Autowired
private ArticleService articleService;
@Autowired
private UserService userService;
@RequestMapping(value = "/addArticle/{id}", method = RequestMethod.GET)
public String addArticle(@PathVariable Integer id, Model model){
User user = userService.getUserById(id);
Article article = new Article();
model.addAttribute("user", user);
model.addAttribute("article", article);
return "addArticle";
}
@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
public ModelAndView addArticle(@ModelAttribute Article article) {
ModelAndView mav = new ModelAndView();
articleService.addArticle(article);
mav.setViewName("redirect:/success");
return mav;
}
}
は、どのように私はそれがとても
<form:input path="userId" disabled="true"></form:input>
は、ユーザIDの値を保持します作るのですか、この
ArticleControllerはのように見えますか? IDを渡す必要があるのか、それともユーザーオブジェクトでなければならないのでしょうか?
この方法で何を変更する必要がありますか?
public ModelAndView addArticle
私はあなただけのIDを入力し、実際のオブジェクトを渡し、名前でそれに代わるものではありませんので、私はpath="userId"
を削除しますMySQLと春データにJPA
http://stackoverflow.com/a/7730719/1356423 –
@Alanその部分を削除しましたが、問題は実際にはありませんでした。とにかくリンクに感謝します。 –