2017-01-10 1 views
1

現在、私はスプリングフォーム複数選択でモデルをバインドしようとしていますが、エラーが発生しています。スプリングフォーム複数選択でモデルデータをバインドする方法

次のように製品モデル:次のように

@Entity 
    public class Product implements Serializable { 

     private static final long serialVersionUID = -3532377236419382983L; 

     @Id 
     @GeneratedValue(strategy = GenerationType.AUTO) 
     private int productId; 

     @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
     @JsonIgnore 
     private List<CartItem> cartItemList; 

     @ManyToOne 
     @JoinColumn(name = "categoryId") 
     @JsonIgnore 
     private Category category; 

     @ManyToMany 
     @JsonIgnore 
     @JoinTable(name="PRODUCT_SUBCATEGORY", 
        joinColumns={@JoinColumn(name="productId")}, 
        inverseJoinColumns={@JoinColumn(name="subCategoryId")}) 
     private List<SubCategory> subCategoryList; 


     public List<SubCategory> getSubCategoryList() { 
      return subCategoryList; 
     } 

     public void setSubCategoryList(List<SubCategory> subCategoryList) { 
      this.subCategoryList = subCategoryList; 
     } 
Getter Setter... 

サブカテゴリモデル:次のように

@Entity 
public class SubCategory implements Serializable { 


    private static final long serialVersionUID = 7750738516036520962L; 

    @Id 
    @GeneratedValue 
    private int subCategoryId; 

    @NotEmpty(message = "The subcategory name must not be empty") 
    @Size(min = 3, max = 20, message = "Minimum 3 to 20 characters allowed") 
    private String subCategoryName; 

    @ManyToOne 
    @JoinColumn(name="categoryId") 
    private Category category; 
Getter and Setter... 

コントローラクラス:次のように

@Controller 
@RequestMapping("/admin") 
public class AdminProduct { 

    private Path path; 

    @Autowired 
    private ProductService productService; 

    @Autowired 
    private SubCategoryService subCategoryService; 

    @Autowired 
    private CategoryService categoryService; 

    @RequestMapping("/product/addProduct") 
    public String addProduct(Model model){ 
     Product product = new Product(); 
     model.addAttribute("product", product); 

     return "addProduct"; 
    } 
    @ModelAttribute("subCategoryName") 
    public Map<Integer, String> populateSubCategoryTypes() { 
     Map<Integer, String> subCategoryNameMap = new HashMap<Integer, String>(); 
     List<SubCategory> subCategoryList = this.subCategoryService.getAllSubCategroy(); 
     for (SubCategory subCategory : subCategoryList) { 
      subCategoryNameMap.put(subCategory.getSubCategoryId(),subCategory.getSubCategoryName()); 
     } 
     return sortByValue(subCategoryNameMap); 
    } 

    public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { 
     List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
       map.entrySet()); 
     Collections.sort(list, new Comparator<Map.Entry<K, V>>() { 
      public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { 
       return (o1.getValue()).compareTo(o2.getValue()); 
      } 
     }); 

     Map<K, V> result = new LinkedHashMap<K, V>(); 
     for (Map.Entry<K, V> entry : list) { 
      result.put(entry.getKey(), entry.getValue()); 
     } 
     return result; 
    } 

addProduct.jsp:

<form:form action="${pageContext.request.contextPath}/admin/product/addProduct" 
        method="post" commandName="product" enctype="multipart/form-data"> 
      <div class="form-group"> 
      <label for="category.categoryName">Category Name*</label> 
      <form:select id="categoryName" path="category.categoryId" class="form-Control"> 
       <form:options items="${categoryName}" /> 
      </form:select> 
      </div> 

      <div class="form-group"> 
      <label for="subCategoryList">SubCategory Name*</label> 
      <form:select items="${subCategoryName}" multiple="true" path="subCategoryList" class="form-Control" /> 
      </div> 
     <input type="submit" value="submit" class="btn btn-default"> 
     <a href="<c:url value="/admin/productInventory" />" class="btn btn-default">Cancel</a> 

    </form:form> 

私のコードを実行すると、Select BoxとSubCategoryでカテゴリが複数選択ボックスに表示されます。しかし、私はSubmitボタンをクリックすると、私はSubCategoryのnullを取得します。私はitemvalueとITEMIDを追加することにより、以下のようなsubcategroyをバインドしようとすると、私は

<form:select items="${subCategoryName}" itemValue="subCategoryId" itemLabel="subCategoryName" multiple="true" path="subCategoryList" class="form-Control" /> 

エラーのエラーを取得

enter image description here

org.springframework.beans.NotReadablePropertyException: Invalid property 'subCategoryId' of bean class [java.lang.Integer]: Bean property 'subCategoryId' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

I have already subCategoryId and subCategoryName property in my SubCategory Model class.

私が結合しない方法で助けてください私のデータは、選択されたサブカテゴリの値を取得します。

ありがとうございました。私は示唆しています唯一の変更はform:selectタグから属性itemValueitemLabelを削除していることを

+0

サブカテゴリクラスを表示できますか? – shark

+0

@shark、サブカテゴリモデルを編集して追加しました。親切に私を助けてください。 – soewin

答えて

1

<form:select items="${subCategoryName}" multiple="true" path="subCategoryList" class="form-Control" />

<form:select items="${subCategoryName}" itemValue="subCategoryId" itemLabel="subCategoryName" multiple="true" path="subCategoryList" class="form-Control" />

を交換して注意してください。

理由

Spring docsから、私は次のように引用しています:

The items attribute is typically populated with a collection or array of item objects. itemValue and itemLabel simply refer to bean properties of those item objects, if specified; otherwise, the item objects themselves will be stringified. Alternatively, you may specify a Map of items, in which case the map keys are interpreted as option values and the map values correspond to option labels. If itemValue and/or itemLabel happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value.

特に太字のテキストを参照してください。

コードサンプルから、モデル属性 'subCategoryName'はIntegerキーとString値のマップであるようです。したがって、マップであるモデル属性については、上のSpringドキュメントからの引用によれば、マップキーは自動的にオプション値として解釈され、対応するマップ値は対応するオプションラベルとして自動的に解釈されます。そのため、itemValueitemLabelを指定する必要はありません。しかし、あなたはまだそれを指定しています。上の引用符の太字の2行目のように、itemValueで指定したものは、マップキーのBeanプロパティとして解釈されます。これはintegerです。そのため、Springは 'subCategoryId'フィールドとそのゲッターをIntegerクラスに見つけようとしているため、失敗してエラーをスローします。

+0

ありがとう、私はこのコードのように変更してみました[]ボタンを押してフォームのポストアクションを行うと、私はデバッグして、私のsubCategoryがnull値を持つことを発見しました。製品モデルにサブカテゴリモデルがあることをフォームが認識していない可能性があります。提案してください。 – soewin

+0

あなたのフォームバッキングオブジェクトは "product"で、フォームの 'path'属性:selectタグは" subCategoryList "です。したがって、 "subCateogorList"のタイプは 'List 'でなければなりません。しかし、あなたが持っているのは 'List 'です。あなたはそれを修正する必要があります。 – VHS

+0

商品モデルでもわかるように、カテゴリモデルと同じことをしました。なぜカテゴリが機能し、サブカテゴリーが機能しないのか、例としてhttp://websystique.com/springmvc/springmvc-hibernate-many-to-many-example-注釈を使用する結合テーブル/ App_UserにはUser_Profilesがありますが、リンクの投稿とほとんど同じでしたが、私とは連携しません。 – soewin

関連する問題