java - 单击提交后如何用数据填充两个实体

标签 java spring spring-mvc spring-data-jpa thymeleaf

我整天都在寻找解决方案,但仍然找不到任何东西。

当我创建一本书时,如何同时创建作者并将其分配给一本书?

我有两个实体

预订

@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/

相关文章:

java - 如何限制可输入的字符数? ( java )

java - 如何修复 `android.app.Application cannot be cast to` 错误

java.sql.SQLTransientConnectionException : spring HikariCP - Connection is not available, 请求超时后

Java 和 Spring MVC 社交艺术分享网站的设计和架构

Java-Servlet : Streaming of a Quicktime-video causes a ClientAbortException

java - 如何解决错误 "The following classes could not be excluded because they are not auto-configuration classes"?

java - 无法打开 ServletContext 资源 [/WEB-INF/mvc-dispatcher-servlet.xml]

java - 如何在 Spring MVC 的 POST 方法中获取原始响应(参数数组)?

java - MediaType HTML 的 HttpMediaTypeNotAcceptableException

java - 如何在java中获取调用层次结构