我正在尝试制作一个web表单,它获取表单数据并将它们添加到多对多数据库(图书和作者)。
当我保存web表单时,我得到:
nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.testwork.bookarchiveapp.entity.Author' for property 'authors[0]': no matching editors or conversion strategy found]"
问题可能是,我使用表单不正确,因为没有表单,我可以将“author”添加到book->list authors和数据库中。该表单也适用于“title”、“year”、“publisher”字段。
这是book类(不包括所有getter和setter,但它们在那里):
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "title")
private String title;
@Column(name = "year")
private int year;
@Column(name = "publisher")
private String publisher;
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH})
@JoinTable(
name = "book_author",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id")
)
private List<Author> authors;
这些是web窗体的控制器:
@GetMapping("/add-book")
public String showFormForAdd(Model theModel){
Book book = new Book();
theModel.addAttribute("book", book);
return "book-form";
}
@PostMapping("/saveBook")
public String saveBook(@ModelAttribute("book") Book book){
bookService.saveBook(book);
return "redirect:/books/list";
}
这是我的网页表单:
<form:form action="saveBook" modelAttribute="book" method="post">
<form:hidden path="id" />
<div class="form-group">
<label>Title</label>
<form:input class="form-control" path="title" value="" placeholder="Enter title"/>
</div>
<div class="form-group">
<label>Author('s)</label>
<form:input class="form-control" path="authors" placeholder="Enter one or more authors separated with comma"/>
</div>
<div class="form-group">
<label>Year</label>
<form:input class="form-control" path="year" placeholder="2020"/>
</div>
<div class="form-group">
<label>Publisher</label>
<form:input class="form-control" path="publisher" placeholder="Enter publisher"/>
</div>
<div id="button-container" class="d-flex justify-content-center">
<input type="submit" value="Save" class="btn btn-primary"/>
</div>
</form:form>
如果我做对了,那是因为表单“authors”get作为字符串传递,而程序不知道如何处理它。我也不知道该怎么处理。我们的计划是得到这个字符串,把它分成几个部分,然后作为一个或多个作者添加它,但我就是不明白怎么做。我不知道如何提取“作者”字段。如果我尝试将其更改为其他内容,它无论如何都会从“books”类请求一个方法。
暂无答案!
目前还没有任何答案,快来回答吧!