一尘不染

如何在弹簧中保存许多对象

jsp

@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的Set中获取索引为0的元素,使用属性路径’voceMenuList [0]’访问


阅读 274

收藏
2020-06-08

共1个答案

一尘不染

集合的元素不能通过索引访问。您将需要添加一些方法来返回包装您的集合的列表。

@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>
2020-06-08