【问题标题】:Thymeleaf display list of authors of the bookThymeleaf 显示本书作者列表
【发布时间】: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


    【解决方案1】:
    <table>
        <span th:each="b: ${model.books}">
            <td>
                <tr th:each="a: ${b.authors}">
                    <p th:text="${a.name}"></p>
                </tr>
            <td>
        </span>
    </table>
    

    试试嵌套循环!

    【讨论】:

    • 如果我希望它看起来像: Book1 : author1, author2, author3, etc.. ; Book2: author1, author3, etc.. ?
    • Nvm,明白了!谢谢你的帮助伙伴:)
    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 2019-11-16
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多