5

我正在尝试使用 spring 的 select 标记来选择多个选项来填充列表。我的选择标签显示良好,当我选择选项时,列表已正确更新。

我遇到的唯一问题是,当我使用已填充的列表渲染 for 时,我的选择标签不会突出显示选定的选项。我尝试调试并且我可以看到列表不是空的,它实际上是似乎没有将选定选项标记为选定的标签。

我的代码:

@Entity
public class ProductsGroup
{
    @Version  @Column(name = "version")
    private Integer version;
    @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id")
    private Integer id;

    @ManyToMany(fetch = FetchType.EAGER)
    private List<Product> products; 

    public List<Product> getProducts()
    {
        return products;
    }

    public void setProducts(List<Product> products)
    {
        this.products = products;
    }
}

@Entity
public class Product
{
    @Version @Column(name = "version")
    private Integer version;

    @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id")
    private Long id;

    private String name;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

<form:form action="${action}" class="fancyform" commandName="productsGroup" id="productForm">
    ....
    <form:select path="products" items="${products}" itemLabel="name" itemValue="id" multiple="true"/>
    ....
</form:form>
4

1 回答 1

9

It's probably due to the fact that the list of selected products doesn't contain the same instances as the complete list of displayed products.

The tag compares products with equals(), and you have not overridden equals() (and hashCode()) in your Product class.

So even if the selected products contain the Product with the name "foo", and the complete list of Product also contains a Product with the name "foo", those products are not equal, and Spring thus doesn't know they're the same product, and that this product should thus be selected.

于 2012-05-28T06:49:59.317 回答