2016-10-06 122 views
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

+0

http://stackoverflow.com/a/7730719/1356423 –

+0

@Alan我刪除了那部分,但問題並不存在。無論如何感謝鏈接。 –

回答

1

我會刪除path="userId",因爲您只需輸入ID和不通過一個實際的對象,並用名稱替換它

<form:input name="userId"></form:input> 

然後您可以將HttpServletRequest request作爲附加參數添加到您的addArticle類中

public ModelAndView addArticle(HttpServletRequest request, @ModelAttribute Article article) { 

這應該允許您從您的形式訪問用戶名和retrive用戶

User user = userService.getUserById(id); 

然後你要設置用戶

Article article = new Article(); 
article.setUser(user) 
相關問題