Java – use ‘select’ tags and entities in thymeleaf
I am creating a form with a select tag as follows:
<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>
The domainclassconverter class of spring data JPA helps me to automatically convert the selected ID to the entity product when I submit the form The product should also not be null (I use @ notnull in the product field of the version class)
My problem – when I came back to edit the data, no product was selected
If I modify the selection like this (th: field and th: errors): < - ps.s 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 when I come back to edit it, it will be selected, but the verifier will not work (the product is always instantiated, even if the selected ID is null)
It looks like a very common scenario (select an entity from the list), but I can't find any good examples Please share your secret knowledge
Solution
It's settled The problem is that I didn't override the equals () and hashcode () methods