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("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:

<th>Title original</th>
<th>Premiere date</th>
<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>


Also my Book (entity) model class:

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

@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
<span th:each="b: ${model.books}">
        <tr th:each="a: ${b.authors}">
            <p th:text="${a.name}"></p>

Try a nested loop!