0

There are 2 related entities in a Hibernate JPA project:

@Entity
public class Order {
    @Id @GeneratedValue(generator="order_sequence", strategy=GenerationType.IDENTITY)
    private int id;
}

and

@Entity
public class OrderItem {
    @Id @GeneratedValue(generator="orderitem_sequence", strategy=GenerationType.IDENTITY)
    @ManyToOne(cascade = CascadeType.ALL)
    private Order order;
    //....
}

With some detailed code ignored, I tried to merge a new Order instance with a List of OrderItem instances in cascade manner, i.e. merge the List<OrderItem> with an EntityManager - "em" in one go without merge the new Order:

for (OrderItem orderItem: orderItemList) {
    em.merge(orderItem);
}

But encountered error when the size of the List<OrderItem> is greater than 1: Unique index or primary key violation since the same Order is merged multiple times when merging each Order instance.

Question: How to resolve this error without merge the Order instance explicitly as a separate merge?

Rui
  • 3,454
  • 6
  • 37
  • 70
  • Does the `Order` have a list of `OrderItem`s as field? If yes, why not just merge the `Order`? – XtremeBaumer May 30 '22 at 06:12
  • @XtremeBaumer No, only the `OrderItem` has dependency on the `Order`, not the other way around, so it is a unidirectional dependency relatioship – Rui May 30 '22 at 06:17
  • According to [this website](https://www.coderscampus.com/hibernate-manytoone-unidirectional-tutorial/), you could try to save instead of merging. This would force you to manage the insert or update yourself – XtremeBaumer May 30 '22 at 06:27
  • @XtremeBaumer Thanks a lot first for the tip. But the link you sent used the ``hibernate.SessionFactory`, so do it mean that by using `EntityManager`, I would be forced to avoid using `CascadeType.ALL` and then insert `Order` and list of `OrderItem`s separately? – Rui May 30 '22 at 09:02
  • [There is no difference](https://stackoverflow.com/a/5640796/7109162). `EntityManager` and `SessionFactory` work basically the same. It seems to come down to what method you call. For `EntityManager` you would probably call `persist()` method instead of the `merge()` – XtremeBaumer May 30 '22 at 09:18
  • @XtremeBaumer Did you see the error, `Unique index or primary key violation`, I mentioned in the question? So does it mean that this error is caused by the call on `merge()` and using `persist()` will prevent this error? Thanks in advance – Rui May 30 '22 at 09:32
  • @XtremeBaumer Indeed I tried to use `persist()` instead of `merge()` and it works :) Thanks a lot. So if you answer it, I would confirm the correctness – Rui May 30 '22 at 18:42

0 Answers0