gpt4 book ai didi

java - 将 JPA 实体表数据显示到 thymeleaf View

转载 作者:行者123 更新时间:2023-11-29 08:39:27 24 4
gpt4 key购买 nike

我有一个带有 id 和 name 列的 JPA 实体表。我想将名称值显示到 thymeleaf View 。现在我可以在 View 中看到实体对象,但看不到名称的列值。以下是我如何创建表并定义 getter 和 setter:

@Entity
@Table(name = "Book")
public class Book extends AbstractPersistable<Long> {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

public Long getID() {
return this.id;
}

public String getContent() {
return this.name;
}

public void setID (Long id) {
this.id = id;
}

public void setContent (String name) {
this.name = name;
}
}

这就是我尝试在 Controller 中设置内容的方式:

@Controller
@RequestMapping("/")
public class BookController {

@Autowired
private BookRepository bookRepository;

@RequestMapping("/addBook")
@ResponseBody
public String addBook(@RequestParam("name") String name) {
Book book = new Book();

book.setContent(name);
bookRepository.save(book);
return name;

}

@RequestMapping(value = "book", method = RequestMethod.GET)
public String books(Model model) {
model.addAttribute("books", bookRepository.findAll());
return "book";
}

}

thymeleaf View 模板:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head lang="en">
<meta charset="UTF-8" />
<title>Books</title>
</head>
<body>
<h1>Books Database</h1>
<ul th:each="book : ${books}">
<li th:text="${book.name}"></li>
</ul>
</body>
</html>

当我从 addBook 页面添加新书并访问该书页以查看书名时,出现此错误:

Exception evaluating SpringEL expression: "book.name". In the IDE console the error found as: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'name' cannot be found on object of type 'sec.book.BookNames.

有什么问题吗?

在 View 中,如果我使用 th:text="${book},那么表中的每一行都会显示一个实体对象列表,如下所示:

Entity of type sec.helloworld.Book with id: null.

我只想显示书名而不是对象。我应该怎么做?

最佳答案

名称的 Yoor getter 必须命名为 getName() 才能被 ExpressionLanguage(SpEL = Spring Expresion Language) 找到。setter 也应该是 setName。

关于java - 将 JPA 实体表数据显示到 thymeleaf View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41394458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com