Book.java
package pl.spring.guru.spring5webapp.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
private String isbn;
@OneToOne
private Publisher publisher;
@ManyToMany
@JoinTable(name = "author_book", joinColumns = @JoinColumn(name =
"book_id"), inverseJoinColumns = @JoinColumn(name = "author_id"))
private Set<Author> authors = new HashSet<>();
public Book() {
}
public Book(String title, String isbn, Publisher publisher){
this.title=title;
this.isbn=isbn;
this.publisher=publisher;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
}
BookController.java
package pl.spring.guru.spring5webapp.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pl.spring.guru.spring5webapp.repositories.BookRepository;
@Controller
public class BookController {
private BookRepository bookRepository;
public BookController(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@RequestMapping(value = "/books")
public String getBooks(Model model){
model.addAttribute("books",bookRepository.findAll());
return "books";
}
}
books.html-百里香模板
<!DOCTYPE html>
<html lang="en" xmlns:th=”http://www.thymeleaf.org”>
<head>
<meta charset="UTF-8">
<title>Spring Framework Guru</title>
</head>
<body>
<h1>Books list</h1>
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
</tr>
<tr th:each="book : ${books}">
<td th:text="${book.id}">123</td>
<td th:text="${book.title}">Spring in Action</td>
<td th:text="${book.publisher.name}">Wrox</td>
</tr>
</table>
</body>
</html>
当我尝试转到localhost / books时,我会得到
异常评估SpringEL表达式:“ book.id”(模板:“ books” -第16行,第13行)
我刚刚学习Spring,并且开始使用spring框架大师教程。我也不明白,为什么需要在book.java中添加一个空的构造函数。没有它,我有下一个问题:
没有默认的实体构造函数: pl.spring.guru.spring5webapp.model.Book;嵌套异常为 org.hibernate.InstantiationException:没有默认的构造函数 实体:: pl.spring.guru.spring5webapp.model.Book
答案 0 :(得分:2)
您缺少ID的获取者。否则,模板引擎将无法访问它。
关于默认构造函数-Spring要求创建实体实例。如果没有可用的默认构造函数,Spring应该如何知道要使用哪些参数。
除了本教程之外,您还应该查看Spring Framework参考文档。阅读很多东西,但是特别是对DI基础进行了很好的解释。