0
我有2個單位用戶和第二十多對一。如何將一個對象與另一個對象關聯?
用戶
@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看起來像這樣
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的價值?我甚至需要傳遞一個id,還是必須是一個用戶對象?
這個方法需要改變什麼?
public ModelAndView addArticle
我使用MySQL和彈簧數據的JPA
http://stackoverflow.com/a/7730719/1356423 –
@Alan我刪除了那部分,但問題並不存在。無論如何感謝鏈接。 –