EntityExistsException when reset a ArrayList and refill before merge

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.