我整天都在寻找解决方案,但仍然找不到任何东西。
当我创建一本书时,如何同时创建作者并将其分配给一本书?
我有两个实体
预订
@Data
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne
private Author author;
}
作者
@Data
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private Set<Book> books;
}
Controller
@Controller
public class BookController {
private BookRepository bookRepository;
public BookController(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@RequestMapping(value="/booklist", method= RequestMethod.GET)
public String bookList(Model model) {
model.addAttribute("books", bookRepository.findAll());
return "booklist";
}
@RequestMapping(value = "/add")
public String addBook(Model model){
model.addAttribute("book", new Book());
return "addbook";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(Book book){
bookRepository.save(book);
return "redirect:booklist";
}
}
查看
<body>
<div>
<form th:object="${book}" th:action="@{save}" action="#" method="post">
<label for="title">Title</label>
<input type="text" id="title"
th:field="*{title}" />
<label for="author">Author</label>
<input type="text" id="author" th:field="*{author.name}" />
<input type="submit" value="Save"></input>
</form>
</div>
</body>
当我尝试创建一本书时,出现此错误
出现意外错误(类型=内部服务器错误,状态=500)。
org.hibernate.TransientPropertyValueException:对象引用未保存的 transient 实例 - 在刷新之前保存 transient 实例
点击提交按钮后 it should look like this
最佳答案
尝试向像这样的实体中的 Author 添加 cascede
@Data
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne(cascade=CascadeType.ALL)
private Author author;
}
或在您的实体上使用 prepersist 注释
@PrePersist
protected void onCreate() {
//check author is exist if not persist the author first
}
关于java - 单击提交后如何用数据填充两个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856491/