2

I am working on a e-library app with spring boot which allows users to order books (these data is saved in OrderDetails table ). Whenever I am trying to save ordered book for a certain user, it gives me the following exception:

org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.springboot.library.domains.OrderDetails.book]


Here is the OrderDetails class:

@Entity
 public class OrderDetails{

    @EmbeddedId
    private OrderDetailsKey key;

    @ManyToOne
    @MapsId("bookId")
    @JoinColumn(name = "book_id")
    private Book book;

    @ManyToOne
    @MapsId("userId")
    @JoinColumn(name = "app_user_id")
    private AppUser appUser;

    private Integer quantity;

    public void setBook(Book book) {
    this.book = book;

}

     // other getters and setters

}

The Book Class

@Entity
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", insertable = false, updatable = false)
private Long id;

private String isbn;

private String title; 

//some other fields

@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private Set <OrderDetails> orderDetails;

//getters and setters
**strong text**}

Based on some similar examples I saw, I need to initialize book property in OrderDetails class, but I'm not sure how to do that:

Something like this except that setOrderDetails method expects a Set<OrderDetails> and I'm passing a single one and that's where I'm stuck

public void setBook(Book book) {
    this.book = book;
    book.setOrderDetails(this);

}

I would really appreciate any help :)

shizhen
  • 12,251
  • 9
  • 52
  • 88
Bella
  • 21
  • 1
  • 2

1 Answers1

0

Usually, that happens when trying to persist an @Entity that has no @Id annotated, which is the case. That error simply means that, when hibernate tries to persist, it is trying to come up with an PRIMARY KEY property, and it fails because that comes from the Book object, which is null.

Consider debugging your code to the point of persistence, and checking there if the entity to be persisted (OrderDetails) has a non-null primary key (Book).

On the second question:

Based on some similar examples I saw, I need to initialize book property in OrderDetails class, but I'm not sure how to do that:

What you wrote is correct. You simply need to give the OrderDetails object a Book object to work with. Since the OrderDetails object has a Book property (which is correct), you simply need to write a "setter", which is a method to set an inner property of the object, on the OrderDetails object, like you already did.

Also, since you have a bidirectional relationship between OrderDetails and Book, consider using the mappedBy annotation.

Gabriel Robaina
  • 709
  • 9
  • 24