单击提交

时间:2018-10-17 13:48:09

标签: 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
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:对象引用了一个未保存的临时实例-在刷新之前保存该临时实例

点击提交按钮后 it should look like this

1 个答案:

答案 0 :(得分:1)

尝试在这样的实体中为作者添加cascede

.introjs-fixParent {
  position: absolute !important;
}

或在实体上使用prepersist注释

@Data
@Entity
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;

@ManyToOne(cascade=CascadeType.ALL)
private Author author;

}