Pregunta

I have the following situation with Java persistence:

public ReturnCodes startWork() {

    sessionBackup = (BaseService<Backup>) ctx.lookup("XYZ/BackupServiceImpl/local");

    Backup backup = new Backup();
    backup.setStatus(BackupStatus.EXECUTING);
    ....
    sessionBackup.save(Backup) //at this point is not actualy saved into DB

    ....//try to connect somewhere
    if ( !ConnectSuccess) {
        sessionBackup.remove(backup);
        return ReturnCodes.REQUESTABORT
    }
    ....
}

@Stateless
public class BackupServiceImpl extends BaseServiceImpl<Backup> implements
    BaseService<Backup>
{

    @Override
    protected Class<Backup> getEntityClass()
    {
        return Backup.class;
    }
}

And the save and remove methods of BaseServiceImpl:

public abstract class BaseServiceImpl<T extends Serializable> implements
    BaseService<T>
{

  protected EntityManagerFactory emf;

  public T save(T entity)
  {
    EntityManager em = emf.createEntityManager();
    em.persist(entity);

    return entity;
  }

  public void remove(T entity)
  {
    EntityManager em = emf.createEntityManager();
    try
    {
      final Method method = getEntityClass().getMethod("getId");
      final String id = (String) ((T) method.invoke(entity));
      entity = em.find(getEntityClass(), id);
      em.remove(entity);
    }
    catch (final Exception ex)
    {
      logger.log(Level.WARNING, "Unexpected error", ex);
    }
  }
}

I don't want to save into the DB in case ConnectSuccess fails, but the remove method fails to find the entity (because is not yet into the DB), and after returning ReturnCodes.REQUESTABORT the entity is saved. How can I cancel the save?

¿Fue útil?

Solución

In general in this case you do a setRollbackOnly().

You may also throw an exception which will trigger the rollbackonly.

See http://www.developerscrappad.com/547/java/java-ee/ejb3-x-jpa-when-to-use-rollback-and-setrollbackonly/

By the way doing this in your code:

catch (final Exception ex)
{
  logger.log(Level.WARNING, "Unexpected error", ex);
}

is too broad and will block rollback functionality.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top