Search code examples
hashcodelombok

Lombok.hashCode issue with "java.lang.StackOverflowError: null"


I have two tables has one to one relationship as below:

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

I used a Form to input data as below

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookForm {
  Book book;
  BookDetail bookDetail;
}

The controller looks like this:

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

Last is my form as below:

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

everything seems no problems, but when I "bookService.save(bookForm.getBook()));" is executed, I got error as below

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]

repeat the same as above about 100 lines.... do this mean that I can't use Lombok.hashCode?

Saved Book: '32768','Spring JPA','32768' Saved BookDetail: '32768','1157'


Solution

  • You have a circular dependency between book and bookdetails. You probably need to exclude book from BookDetail or bookDetail from Book.

    You can add @EqualsAndHashCode(exclude="book"). For more information, see the EqualsAndHashCode documentation.