Search code examples
htmlspringjpathymeleaf

th:each loop doesnt work


I have problem with th:each. It doesn't looping. I try fix it for long time and I searched many topic with the same problem but it still doesn't work. So I ask here for info how fix it.

Nothing display from the list (First and Second) on webpage so i think that with this is something wrong

<ul th:each="author : ${book.authors}">

Book class:

@ManyToMany(mappedBy = "books")
     private Set<Author> authors = new HashSet<>();

Author class:

@ManyToMany
    @JoinTable(name = "author_books",
            joinColumns = @JoinColumn(name = "book_id"),
            inverseJoinColumns = @JoinColumn(name= "author_id"))
    private Set<Book> books = new HashSet<>();

HTML code:

<td>
    <ul th:each="author : ${book.authors}">
        <li>First</li>
        <li>Second</li>
        <li  th:text="${book.getAuthorsN()}">Author</li>
    </ul>
</td>`

=======UPDATE=======

Controller:

@Controller
public class BooksController {

private final BookService bookService;

public BooksController(BookService bookService) {
    this.bookService = bookService;
}

@RequestMapping("/books/home")
public String showBooks(Model model){

    model.addAttribute("books", bookService.getBooks());

    return "books/home";
}

}


Solution

  • To get displayed the book's properties (like getAuthorsN()), you should iterate through the books list, not the authors, e.g.:

    <ul th:each="book : ${author.books}">
        <li>First</li>
        <li>Second</li>
        <li th:text="${book.getAuthorsN()}">Author</li>
    </ul>
    

    Also probably in your Author class you should change object's primary key (joinColumns), and a foreign key to the target object's primary key (inverseJoinColumns) to hold the relationship between Author and Book:

    @JoinTable(name = "author_books",
            joinColumns = @JoinColumn(name = "author_id"),
            inverseJoinColumns = @JoinColumn(name= "book_id"))
    

    Read more about ManyToMany relationship.