I have a strange bug in UI part of my pet-app (Java+Spring+Themeleaf+Bootstrap) with Dto edit. Dto looks like (int id, String name, List list). I try checkbox and select to edit List and in both case result the same: if in list only one dto, then it correctly shows in checkbox or selection list,
but if list contain more than one, no one option choosed.
When I choose any options(multiselect allows), and press Save- Dto saves in Data base correctly.
<div class="form-group">
<label class="col-form-label">Select courses:</label>
<div class="col-sm-10">
<input type="hidden" th:field="*{id}"/>
<div th:each="course : ${allCourses}">
<input type="checkbox" th:id="${{course}}" th:value="${{course}}" th:field="*{courses}" />
<label th:for="${{course}}" th:text="${course.name}">Course</label>
</div>
<span class="font-italic text-danger" th:if="${#fields.hasErrors('courses')}"
th:errors="*{courses}"></span>
</div>
</div>
What I need to change in code to fix this bug?
You need to override the equals & hashCode methods for this DTO strictly like this:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DTO)) return false;
DTO dto = (DTO) o;
return getId().equals(dto.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}