我遇到了问题。我希望将数据库中的所有图书显示为列表,更重要的是,每个人都会显示其作者的列表。这就是我的控制器方法的样子:
@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);
}
但我不知道如何将图书与作者链接以在我的视图中正确显示:
<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>
我的图书(实体)模型类:
@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>();
答案 0 :(得分:2)
<table>
<span th:each="b: ${model.books}">
<td>
<tr th:each="a: ${b.authors}">
<p th:text="${a.name}"></p>
</tr>
<td>
</span>
</table>
尝试嵌套循环!