I have 2 entities User and Article
User
@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;
Article
@Entity
@Table(name = "article")
public class Article {
@Id
@GeneratedValue
private Integer articleId;
private String name;
@ManyToOne
@JoinColumn(name = "user_id")
private User userId;
I can register a user then go to his page and from there go to a page that has a form for submitting an article.
<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>
The problem is, I don't know how to associate the article with that user. For now my ArticleController looks like this
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;
}
}
How do I make it so
<form:input path="userId" disabled="true"></form:input>
will hold the value of user id? Do I even need to pass there an id or does it have to be an user object?
What do I have to change in this method?
public ModelAndView addArticle
I'm using mysql and spring data jpa