java 对 Thymeleaf 中的实体使用“选择”标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15227680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:55:11  来源:igfitidea点击:

Using 'select' tag with entities in Thymeleaf

javaspring-mvcthymeleaf

提问by Filip Spiridonov

I am creating a form with the select tag that looks like this:

我正在创建一个带有 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>

DomainClassConverterclass of Spring Data JPAhelps to auto-convert selected idto the entity Productwhen I submit the form. The productshould also be not null (I am using @NotNullon the productfield in the Versionclass.

DomainClassConverterclass ofSpring Data JPA有助于在我提交表单时将选定的自动转换id为实体Product。该product也应该是不为空(我用@NotNullproduct领域Version类。

The problem that I have - when I come back to edit the data, the Productis not selected.

我遇到的问题 - 当我回来编辑数据时,Product没有选择。

If I modify the selectlike this (th:fieldand th:errors): <-- p.s. is not a sad smile

如果我select像这样修改(th: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>

then it becomes selected when I come back to edit it, but the validator doesn't work (productis always instantiated, even if selected id is null).

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

It looks like a very common scenario (selecting an entity from the list), but I cannot find any good looking example. Please share the secret knowledge.

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

采纳答案by Filip Spiridonov

Solved. The problem existed because I had not overridden the equals()and hashCode()methods.

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