2011-07-09 62 views
0

我遇到了Restaurant和Tag類之間ManyToMany關係的問題。我:MultipleSelect中的Spring MVC ManyToMany

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 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; 

在我的jsp我:

<form:select multiple="true" path="tags"> 
<form:options items="${tagList }" itemValue="id" itemLabel="name" /> 
</form:select> 

在我控制我:

public ModelAndView myrestaurantadd(HttpServletRequest request, 
      HttpServletResponse response, Restaurant restaurant) 
      throws Exception { 
restaurantDAO.saveRestaurant(restaurant); 
} 

當我點擊保存按鈕,我得到錯誤:

字段'標記'的對象'命令'中的字段錯誤:被拒絕的值[[Ljava.lang.String; @ 5babd8cb];代碼[typeMismatch.command.tags,typeMismatch.tags,typeMismatch.java.util.List,typeMismatch];參數[org.springframework.context.support.DefaultMessageSourceResolvable:codes [command.tags,tags];參數[];默認消息[標籤]];默認消息[無法將屬性'tags'的類型[java.lang.String []]的屬性值轉換爲所需類型[java.util.List];嵌套異常是java.lang.IllegalArgumentException:無法將[java.lang.String]類型的值轉換爲屬性'tags [0]'的所需類型[beans.Tag]:找不到與根本原因匹配的編輯器或轉換策略] org.springframework.validation.BindException:org.springframework.validation.BeanPropertyBindingResult:1級的錯誤

回答

0
[Failed to convert property value of type [java.lang.String[]] to required type [java.util.List] for property 'tags'; 

你是如何處理你的控制器對象。您必須在控制器處理程序方法中接受java.util.List,而傳遞的實際對象是String[]。嘗試將其作爲String []處理,並將其轉換爲控制器中的List。

編輯: 關於你的評論,我懷疑這樣的事情。標籤以jsp的形式傳遞給String []標籤,你正在捕獲一個Restaurant對象,這將需要一個List,並因此出現錯誤。請嘗試以下

public ModelAndView myrestaurantadd(HttpServletRequest request, HttpServletResponse response, Restaurant restaurant, String[] tags) throws Exception { 
//Convert the String array into List<Tag> and set this list in the restaurant object 
//Note that the Restaurant object obtained as the method argument with contain a null tag list, so you would need to set the tag list before saving 
//Save the Restaurant object now 
} 
+0

我只在我的控制器:公衆的ModelAndView myrestaurantadd(HttpServletRequest的請求,HttpServletResponse的 響應,餐廳餐廳) 拋出異常{ restaurantDAO.saveRestaurant(餐廳); } – zax

+0

@zax請參閱編輯 –

+0

請參閱http://stackoverflow.com/questions/6637324/save-many-to-many-in-spring-mvc – gouki