【问题标题】:How to save many objects in a spring <form:form>如何在弹簧 <form:form> 中保存许多对象
【发布时间】:2015-02-13 11:06:38
【问题描述】:
@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]' 访问

【问题讨论】:

  • 请您发布您的控制器代码吗?
  • 您的原始问题已得到解答。对于由完全独立的问题引起的任何后续问题,您应该提出一个新问题。
  • 好的,谢谢你的帮助

标签: java spring jsp jstl spring-form


【解决方案1】:

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>

【讨论】:

  • 我根据您的帮助编辑了我的代码。现在我得到一个不同的错误。我不知道我是否没有正确遵循您的建议
  • 您确定传递给 ArrayList 构造函数的 Set 不为空吗?
  • 我编辑了这行代码 private Set voceMenuList = new HashSet ();现在我没有收到任何错误,但是对象 Menu 的字段 voceMenuList 的大小始终为 0。我想知道是否必须为 voceMenuAsList 添加一个 set 方法
  • 您期望由 JPA 层填充的 Set 为 null,这就是它失败的原因。通过添加此语句,您可以防止它为空。为什么它没有从您的 JPA 层中填充是一个单独的问题。如果在 get as list 方法中手动添加了一些 VoceMenu 项目,那么这应该确认您所拥有的内容按预期工作并且问题出在 JPA 层中。如果是这样,那么您的原始问题已得到解决,您应该将答案标记为已接受并围绕 JPA 问题提出一个新问题。
  • 所有,我可以知道如何为这种方法包含 setter 吗?我看到这些值没有被添加。
猜你喜欢
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2022-10-02
  • 2013-11-19
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多