我有2个实体User和Article
用户
@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和spring数据jpa
答案 0 :(得分:1)
我会删除path="userId"
,因为您只输入了ID并且没有传递实际对象并将其替换为名称
<form:input name="userId"></form:input>
然后,您可以将HttpServletRequest request
作为附加参数添加到addArticle类
public ModelAndView addArticle(HttpServletRequest request, @ModelAttribute Article article) {
这应该允许您从表单访问用户ID并检索用户
User user = userService.getUserById(id);
然后你必须设置用户
Article article = new Article();
article.setUser(user)