Tyler Durden Tyler Durden - 2 months ago 8
Java Question

Thymeleaf display list of authors of the book

I'm stuck with a problem. I want to display all of the Books from my database as a list and what is more, for every of them display list of it's Authors. This is how my controller method looks like:

@RequestMapping(value="/new",method = RequestMethod.GET)
public ModelAndView newBooks() {
List<Book> books = bookRepository.findAllByOrderByPremiereDateDesc();
Set<Author> authors = new HashSet<>();
for(Book b:books){
authors = b.getAuthors();

}

Map<String, Object> model = new HashMap<String, Object>();
model.put("books",books);
model.put("authors", authors);

return new ModelAndView("books/new","model",model);
}


but i have no idea how to link books with their authors to display them properly in my view:

<table>
<tr>
<th>Title</th>
<th>Title original</th>
<th>Premiere date</th>
<th>Authors</th>
</tr>
<tr th:each="b : ${model.books}">
<td th:text="${b.title}"></td>
<td th:text="${b.titleOriginal}"></td>
<td th:text="${b.premiereDate}"></td>
<tr th:each="a: ${b.authors}">
<td th:text="${a.name}"></td>
<td th:text="${a.surname}"></td>
</tr>

</table>


Also my Book (entity) model class:

@Entity
@Table(name = "book")
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "book_id")
private int bookId;
@Column(name = "isbn")
private long isbn;
@Column(name = "title")
private String title;
@Column(name = "title_original")
private String titleOriginal;
@Column(name = "premiere_date")
private Date premiereDate;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "book_author", joinColumns = {@JoinColumn(name = "book_id")}, inverseJoinColumns = {@JoinColumn(name = "author_id")})
private Set<Author> authors = new HashSet<Author>();

Answer Source
<table>
<span th:each="b: ${model.books}">
    <td>
        <tr th:each="a: ${b.authors}">
            <p th:text="${a.name}"></p>
        </tr>
    <td>
</span>

Try a nested loop!