EntityExistsException when reset a ArrayList and refill before merge

Hi

I’m facing a issue when I trying to reset and refill an ArrayList before merge. This is the situation:

I have a Collection of PedidoItem in the Pedido entity:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "pedido", orphanRemoval = true)
private List<PedidoItem> itens;

And I’m trying to reset and refill the ArrayList in a process, but I won’t remove or merge at this time, because I need the user complete the whole form before it.

pedido.setItens(new ArrayList<>());

nfeFiltro.getProdutos().stream()
        .forEach(nfeProduto -> {
            PedidoItem pedidoItem = new PedidoItem();
            pedidoItem.setPedido(pedido);

            PedidoItemId pedidoItemId = new PedidoItemId();
            pedidoItemId.setPedidoLinha(nfeProduto.getId().getNfeNumeroDoItem());
            pedidoItem.setId(pedidoItemId);

// fill the pedidoItem

After all when I merge the Pedido entity Hibernate is returning EntityExistsException.

How could I proceed?

Additional information:

PedidoItem Identity:

@Embeddable
public @Data class PedidoItemId implements Serializable {

    @Column(name = "pedido_id", nullable = false)
    private Integer pedidoId;

    @Column(name = "pedido_linha", nullable = false)
    private Integer pedidoLinha;

}
@EmbeddedId
    private PedidoItemId id;

Thanks in advance

There are two ways to fix it:

  1. The fastest way but not the most efficient is to just flush after resetting the collection:

    pedido.setItens(new ArrayList<>());
    
    entityManager.flush();
    
    nfeFiltro.getProdutos().stream()
    		.forEach(nfeProduto -> {
    			PedidoItem pedidoItem = new PedidoItem();
    			pedidoItem.setPedido(pedido);
    
    			PedidoItemId pedidoItemId = new PedidoItemId();
    			pedidoItemId.setPedidoLinha(nfeProduto.getId().getNfeNumeroDoItem());
    			pedidoItem.setId(pedidoItemId);
    
    // fill the pedidoItem
    
  2. The more efficient and the proper way to do it is to merge the old and the new collection so that:

    • items that are both in the old and the new collection should not be removed
    • new items are added from the incoming collection to the managed one
    • old entries that are no longer found in the incoming collection should be removed

For more details, check out this article.