2011-07-09 47 views
2

我在餐廳和標籤之間有很多關係。這裏是我的實體:在Spring MVC中保存多對多

public class Restaurant { 
    @Id 
    @GeneratedValue 
    private int id; 
    (...) 
    @ManyToMany 
    @JoinTable(name="restaurant_tag", 
      joinColumns={@JoinColumn(name="restaurant_id")}, 
      inverseJoinColumns={@JoinColumn(name="tag_id")}) 
    private List<Tag> tags; 

和:

public class Tag { 
    @Id 
    private int id; 
    private String name; 
    @ManyToMany 
    @JoinTable(name="restaurant_tag", 
      joinColumns={@JoinColumn(name="tag_id")}, 
      inverseJoinColumns={@JoinColumn(name="restaurant_id")}) 
    private List<Restaurant> restaurants; 

在我的控制器(添加)我:

public ModelAndView myrestaurantadd(HttpServletRequest request, 
      HttpServletResponse response, Restaurant restaurant, String[] tags) throws Exception { 
     for(String tag : tags){ 
      Tag x = new Tag(); 
      x.setName(tag); 
     restaurant.getTags().add(x); 
     } 

而且在我的jsp:

<form:form action="myrestaurantadd.htm" modelAttribute="restaurant" commandName="restaurant"> 
(...) 
<form:select path="tags" multiple="true" items="${tagList}" itemLabel="name" itemValue="id"/> 

一切顯示確定,我有多個選擇與我的標籤,但當我點擊「保存」,我得到這個錯誤:

> org.springframework.web.util.NestedServletException: 
> Request processing failed; nested 
> exception is 
> org.springframework.beans.BeanInstantiationException: 
> Could not instantiate bean class 
> [[Ljava.lang.String;]: No default 
> constructor found; nested exception is 
> java.lang.NoSuchMethodException: 
> [Ljava.lang.String;.<init>() 
+1

與您的錯誤沒有關係,但您的映射錯誤:通過使用@ManyToMany(mappedBy =「...」),其中一個關聯必須與另一個關聯。請參閱http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e1727。此外,始終初始化關聯的兩端(即添加x.getRestaurants()。add(restaurant)) –

回答

4

你必須確定你的restaurant對象的控制器上的tags屬性自定義屬性編輯器。

@InitBinder 
    protected void initBinder(HttpServletRequest request, 
      ServletRequestDataBinder binder) throws Exception { 

     super.initBinder(request, binder); 

     binder.registerCustomEditor(List.class, "tags",new CustomCollectionEditor(List.class){ 

      @Override 
      protected Object convertElement(Object element) { 
       Tag tag = new Tag(); 

       if (element != null) { 
        Long id = Long.valueOf(element.toString()); 
        tag.setId(id); 
       } 
       return tag; 
      } 
     }); 

    }