5
@Component
@Entity
@Table(name="menu")
@Configurable
public class Menu implements Serializable{      
    ....        
    @OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
    private Set<VoceMenu> voceMenuList; 

    public Set<VoceMenu> getVoceMenuList() {
        return voceMenuList;
    }

    public void setVoceMenuList(Set<VoceMenu> voceMenuList) {
        this.voceMenuList = voceMenuList;
    }
    .....   
}

我打印一个表单来编辑菜单及其相关的 VoceMenu 对象,这样:

<form:form action="editMenu" method="post" commandName="menu"> 
     Menu id<form:input path="id" maxlength="11"/><br/>       
     ...... 
    <c:forEach items="${menu.voceMenuList}" varStatus="counter">            
        <form:input path="voceMenuList[${counter.index}].id" maxlength="11"/>
             .....
    </c:forEach>
    <input type="submit">
</form:form>

但是,当我尝试保存对象菜单时,我收到此错误:

bean 类 [com.springgestioneerrori.model.Menu] 的无效属性“voceMenuList [0]”:无法从大小为 0 的集合中获取索引为 0 的元素,使用属性路径“voceMenuList [0]”访问

4

1 回答 1

12

Set 的元素不能通过索引访问。您将需要添加返回包含您的集合的 List 的方法。

@Component
@Entity
@Table(name="menu")
@Configurable
public class Menu implements Serializable{      
    ....        
    @OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
    private Set<VoceMenu> voceMenus; 

    public Set<VoceMenu> getVoceMenus() {
        return voceMenus;
    }

    public void setVoceMenus(Set<VoceMenu> voceMenus) {
        this.voceMenus = voceMenus;
    }

    //bind to this
    public List<VoceMenu> getVoceMenusAsList(){
        return new ArrayList<VoceMenu>(voceMenus);
    }
    .....   
}

JSP:

<form:form action="editMenu" method="post" commandName="menu"> 
     Menu id<form:input path="id" maxlength="11"/><br/>       
     ...... 
    <c:forEach items="${menu.voceMenusAsList}" varStatus="counter">            
        <form:input path="voceMenusAsList[${counter.index}].id" maxlength="11"/>
             .....
    </c:forEach>
    <input type="submit">
</form:form>
于 2015-02-13T17:49:00.933 回答