我有两个表具有一对一的关系,如下所示:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private int id;

  private String name;

  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "book_dtail_id")
  private BookDetail bookDetail;
}

@Entity
@Table(name = "book_detail")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookDetail {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private Integer id;

  @Column(name = "number_of_pages")
  private Integer numberOfPages;

  @OneToOne(mappedBy = "bookDetail")
  private Book book;
}

我用表格输入数据如下
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookForm {
  Book book;
  BookDetail bookDetail;
}

Controller 如下所示:
String handleNewBook(Model model){
  Book book = new Book();
  BookDetail bookDetail = new BookDetail();
  BookForm bookForm = new BookForm(book, bookDetail);

  model.addAttribute("bookForm", bookForm);
  return "index";
}

String handleSaveBookCreate(BookForm bookForm, Model model){
    bookForm.getBook().setBookDetail(bookForm.getBookDetail());
    bookForm.getBookDetail().setBook(bookForm.getBook());
    bookService.save(bookForm.getBook()));
    return "index";
}

最后是我的表格,如下所示:
<form role="form" action="#" th:object="${bookForm}" th:action="@{/book}" method="POST">
    <input type="text" th:field="*{book.name}"/>
    <input type="text" th:filed="*{bookDetail} == null ? '' : *{bookDetail.numberOfPages}"  placeholder="Enter Book Page Numbers"/>
    <button type="submit">Submit</button>
</form>

一切似乎都没有问题,但是当我“bookService.save(bookForm.getBook()))”时被执行,我得到如下错误
java.lang.StackOverflowError: null,
at com.zangland.study.jpa.entity.BookDetail.hashCode(BookDetail.java:17) ~[classes/:na]
at com.zangland.study.jpa.entity.Book.hashCode(Book.java:16) ~[classes/:na]
at com.zangland.study.jpa.entity.BookDetail.hashCode(BookDetail.java:17) ~[classes/:na]
at com.zangland.study.jpa.entity.Book.hashCode(Book.java:16) ~[classes/:na]

重复与上面相同的大约100行...。这是否意味着我不能使用Lombok.hashCode?

已保存的书:'32768','Spring JPA','32768'
已保存的图书详细信息:“32768”,“1157”

最佳答案

您在book和bookdetails之间有一个循环依赖性。您可能需要从book中排除BookDetail或从bookDetail中排除Book

07-24 20:02