MultiSelect中的Spring MVC ManyToMany

时间:2011-07-09 12:14:37

标签: hibernate spring-mvc many-to-many

我遇到了Restaurant和Tag类之间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);
}

当我点击“保存”按钮时,出现错误:

字段'tags'上对象'command'中的字段错误:被拒绝的值[[Ljava.lang.String; @ 5babd8cb];代码[typeMismatch.command.tags,typeMismatch.tags,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [command.tags,tags];参数[];默认消息[tags]]; default message [无法将类型[java.lang.String []]的属性值转换为属性'tags'的必需类型[java.util.List];嵌套异常是java.lang.IllegalArgumentException:无法将类型[java.lang.String]的值转换为属性'tags [0]'所需的类型[beans.Tag]:找不到匹配的编辑器或转换策略]] org.springframework.validation.BindException:org.springframework.validation.BeanPropertyBindingResult:1个错误

1 个答案:

答案 0 :(得分: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。

编辑: 关于你的评论,我怀疑那种东西。标签以String []标签的形式从jsp传递,你正在捕获一个需要List而因此出错的Restaurant对象。请尝试以下

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
}