Search code examples
javaspringspring-bootspring-data-jpathymeleaf

Make Thymeleaf read object model array


I am using Thymeleaf to read this Spring (JPA) model:

@Entity
@Table(name = "category", schema = "dbo", catalog = "myapp")
public class CategoryEntity {
    private int id; //works
    ...
    private List<BookEntity> books; //doesn't work

    @Id
    @Column(name = "id", nullable = false)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

@OneToMany(mappedBy="category")
    public List<BookEntity> getBooks() {
        return books;
    }

    public void setLineas(List<BookEntityEntity> books) {
        this.books = books;
    }

I included it in the model through the controller such like:

 model.addAttribute("categories", repository.findAll());

I access the fields such like:

 <tr th:each ="category ${categories}">
         <td th:text="${category.id}"></td>
</tr>

And it displays the category id.

But the list field is not being serialized and can't be accessed through Thymeleaf. How can I list the book list as a parameter of the category entity? Can I choose what parameters are processed by Thymeleaf? The purpose is to iterate over books like above:

<tr th:each ="book ${category.books}">
             <td th:text="${book.title}"></td>
</tr>

Solution

  • I just added @Valid annotation to the list and it worked. Seems to be required with special types to avoid listing large amounts of data unnecesarely.

    @Valid
     private List<BookEntity> books;