【发布时间】:2018-01-24 15:32:45
【问题描述】:
我遇到了一个问题。我想将我的数据库中的所有书籍显示为一个列表,此外,每本书都显示它的作者列表。这就是我的控制器方法的样子:
@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>();
【问题讨论】:
标签: java hibernate spring-boot thymeleaf