Lombok.hashCode 出现“java.lang.StackOverflowError: null”问题

问题描述 投票:0回答:3

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

@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;
}

控制器看起来像这样:

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'

java lombok hashcode
3个回答
91
投票

书籍和书籍详细信息之间存在循环依赖关系。您可能需要从

book
中排除
BookDetail
或从
bookDetail
中排除
Book

您可以添加

@EqualsAndHashCode(exclude="book")
。有关更多信息,请参阅 EqualsAndHashCode 文档


21
投票

lambok 导致循环依赖

原因:toString()方法

解决方案: 更换您的其中一个型号

@Getter
@Setter
public class BookDetail

而不是

@Data
public class BookDetail

0
投票

对我有用的解决方案是将此注释添加到您相关的实体中

@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class YourEntityName

如果您希望 lombok 为特定变量生成 equals()Hashcode(),您可以使用 @EqualsAndHashCode.Include 标记它们,否则只需使用我在此处指定的注释标记您的实体即可会解决你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.