Search code examples
javamysqljpaejbeclipselink

Inserting value in DB or update existing one


I'm trying to manage my DB with EclipseLink and I've got a serious problem.

Here's my simple method

    PUEntityManager.getTransaction().begin();
    if (!PUEntityManager.contains(evento)) {
        PUEntityManager.persist(evento);            
    } else {
        PUEntityManager.merge(evento);
        //PUEntityManager.refresh(evento);
    }
    PUEntityManager.getTransaction().commit();

As you can see it's really easy. If the DB contains the entity, I'll merge the changes to store them in the DB, otherwise I just create a new entity.

But it won't work because it throws an exception about duplicate primary ket, even if the contains returns true!

What's wrong with it?


Solution

  • If the entity is being put into the database outside of Eclipselink, then you will need to attempt to load the entity before you persist changes to it. This is the only dependable way to ensure consistency:

    Object primaryKey = evento.getPrimaryKey();
    Object tmpEvento = PUEntityManager.load( Evento.class, primaryKey )
    
    if ( tmpEvento == null )
    {
        tmpEvento = PUEntityManager.persist( evento );
    }
    else
    {
        // If the evento already exists, you need to decide which attributes of
        // the evento in the DB that you want to copy over to the evento
        // you want to merge.  This is only an example.
        tmpEvento.setXXX( evento.getXXX() );
        tmpEvento.setYYY( evento.getYYY() );
        tmpEvento = PUEntityManager.merge( tmpEvento );
    }
    
    // I recommend returning the tmpEvento object after persisting or merging.
    return tmpEvento;