Reputation: 91
I got relation many to many between Restaurant and Tag. Here are my entities:
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;
And:
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;
In my controller (add) I got:
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);
}
And in my jsp:
<form:form action="myrestaurantadd.htm" modelAttribute="restaurant" commandName="restaurant">
(...)
<form:select path="tags" multiple="true" items="${tagList}" itemLabel="name" itemValue="id"/>
everything shows ok, I got multiple select with my tags, but when I click 'save', I got this error:
> 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>()
Upvotes: 2
Views: 3315
Reputation: 4402
You will have to define a custom property editor for the tags
property of your restaurant
object on your controller.
@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;
}
});
}
Upvotes: 4