我想从一个表单中保存2个entity
,author
和book
。我该怎么做?
我知道我必须先保存作者,但我不知道如何。 Author
与book
有一对多关系。
我设置了cascadetype.ALL
。我在用百里香。
<form th:object="${book}" th:action="@{/book/}" method="post">
<input type="hidden" class="form-control" th:field="*{id}"/>
<label>title</label>
<input type="text" class="form-control" th:field="*{title}"/>
<label>isbn</label>
<input type="text" class="form-control" th:field="*{isbn}"/>
<label>description</label>
<input type="text" class="form-control" th:field="*{description}"/>
<label>cat</label>
<ul>
<li th:each="category : ${book.getCategorySet()}" th:text="category.getCategory()"></li>
</ul>
<label>author</label>
<input type="text" class="form-control" th:field="*{author.name}"/>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
authorCommand
@Setter
@Getter
@NoArgsConstructor
public class AuthorCommand {
private long id;
private String name;
private String lastName;
private Set<BookCommand> bookCommandSet = new HashSet<>();
}
bookCommand
@Setter
@Getter
@NoArgsConstructor
public class BookCommand {
private long id;
private String title;
private String isbn;
private String description;
private Set<CategoryCommand> categorySet = new HashSet<>();
private AuthorCommand author;
}
bookController
@RequestMapping(value = "book/new", method = RequestMethod.GET)
public String newBook(Model model){
model.addAttribute("book", new BookCommand());
return "book/form";
}
@RequestMapping(value = "book", method = RequestMethod.POST)
public String saveOrUpdate(@ModelAttribute("book") BookCommand bookCommand){
BookCommand savedBook = bookService.saveBookCommand(bookCommand);
return "redirect:/book/show/"+savedBook.getId();
}
答案 0 :(得分:0)
好吧,您始终可以使用输入中的name
标签发送除模型之外的其他参数。
HTML
<form th:object="${book}" th:action="@{/book/}" method="post">
<input type="hidden" class="form-control" th:field="*{id}"/>
<label>title</label>
<input type="text" class="form-control" th:field="*{title}"/>
<label>isbn</label>
<input type="text" class="form-control" th:field="*{isbn}"/>
<label>description</label>
<input type="text" class="form-control" th:field="*{description}"/>
<label>cat</label>
<ul>
<li th:each="category : ${book.getCategorySet()}" th:text="category.getCategory()"></li>
</ul>
<label>author</label>
<input type="text" class="form-control" name="author"/>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
控制器
@RequestMapping(value = "book", method = RequestMethod.POST)
public String saveOrUpdate(@ModelAttribute("book") BookCommand bookCommand,
@RequestParam("author") String name,
BindingResult bindingResult){
if( bindingResult.hasErrors()) {
return "redirect:/book/new";
}
Author author = new Author();
author.setName(name);
authorService.saveAuthor(author);
savedBook.setAuthor(author);
BookCommand savedBook = bookService.saveBookCommand(bookCommand);
return "redirect:/book/show/"+savedBook.getId();
}
需要考虑的几件事,我不知道您是如何分隔作者姓名的,但是我会添加两个不同的输入,一个用于姓氏,另一个用于姓氏。另外,我假设作者的ID正在使用@GeneratedValue
。