thymeleaf / thymeleaf-spring

Thymeleaf integration module for Spring
http://www.thymeleaf.org
Apache License 2.0
434 stars 156 forks source link

Usin a java record in a thymeleaf form for updating #317

Open ilumar589 opened 11 months ago

ilumar589 commented 11 months ago

Context: I would like to use the new java features like records and eventually value objects to reduce memory footprint in my applications with thymeleaf models. I'm using spring boot 3.2(M3) with thymeleaf-starter As an example:

<form action="#" th:action="@{/updateExistingEmployee}" th:object="${employeeToUpdate}"
          method="POST">

        <!-- Add hidden form field to handle update -->
        <input type="text" th:field="*{id}"/>

        <input type="text" th:field="*{name}" class="form-control mb-4 col-4">

        <input type="text" th:field="*{email}" class="form-control mb-4 col-4">

        <button type="submit" class="btn btn-info col-2"> Update Employee</button>
</form>`
public record Employee(
        long id,
        String name,
        String email,
        ValueEnum valueEnum
) {

    public Employee() {
        this(0, EMPTY_STRING, EMPTY_STRING, ValueEnum.EMPTY);
    }

    public Employee(long id, String name, String email) {
        this(id, name, email, ValueEnum.HAS_VALUE);
    }
}

employeeToUpdate is mapped to the record in the controller model. When I try to update an already existing value and submit the form, the employee model comes with it's empty constructor values instead of the populated ones. I understand why this is happening, because of the immutable nature of records/lack of setters, but I would like to know if there are any plans to support records/value objects in the future for stuff like this. I would like to avoid intermediary normal class dto's just for updating. It defeats the purpose of using them in the first place.

Thank you in advance!