th:每个循环都不起作用

时间:2018-03-17 19:06:07

标签: html spring jpa thymeleaf

我有问题:每个。它没有循环。我尝试修复它很长时间,我搜索了许多相同问题的主题,但它仍然无法正常工作。所以我在这里询问如何修复它。

网页上的列表(第一个和第二个)没有显示任何内容所以我认为这是错误的

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

图书课程:

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

作者类:

@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
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";
}

}

1 个答案:

答案 0 :(得分:0)

要显示book的属性(例如getAuthorsN()),您应该遍历books列表,而不是authors,例如:

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

也可能在您的Author类中,您应该更改对象的主键(joinColumns),以及目标对象的主键(inverseJoinColumns)的外键以保持Author之间的关系{1}}和Book

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

详细了解ManyToMany relationship