在Thymeleaf中使用'select'标签和实体

时间:2013-03-05 15:29:24

标签: java spring-mvc thymeleaf

我正在创建一个带有select标签的表单,如下所示:

<form th:object="${version}" method="post" class="form-horizontal">
    ...
    <div class="control-group" th:classappend="${#fields.hasErrors('product')} ? 'error'">
        <label class="control-label" for="product" th:text="#{version.product}">Product</label>
        <div class="controls">
            <select id="product" th:field="*{product}">
                <option value="" th:text="#{common.select.prompt}"></option>
                <option th:each="p : ${productList}" th:value="${p.id}"  th:text="${p.name}"></option>
            </select>
            <span class="help-inline" th:errors="*{product}"></span>
        </div>
    </div>
    ...
</form>
当我提交表单时,

DomainClassConverter Spring Data JPA类有助于将所选id自动转换为实体Productproduct也应该不为空(我在@NotNull类的product字段中使用Version

我遇到的问题 - 当我回来编辑数据时,Product未被选中。

如果我这样修改selectth:fieldth:errors):<-- p.s. is not a sad smile

<select id="product" th:field="*{product.id}">
    <option value="" th:text="#{common.select.prompt}"></option>
    <option th:each="p : ${productList}" th:value="${p.id}" th:text="${p.name}"></option>
</select>
<span class="help-inline" th:errors="*{product.id}"></span>

然后当我回来编辑它时会被选中,但验证器不起作用(product总是被实例化,即使选择的id是null)。

它看起来像一个非常常见的场景(从列表中选择一个实体),但我找不到任何好看的例子。请分享秘密知识。

1 个答案:

答案 0 :(得分:3)

解决。存在问题是因为我没有覆盖equals()hashCode()方法。