1

Java持久性有以下情况:

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;
    }
}

和方法:save_removeBaseServiceImpl

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);
    }
  }
}

我不想保存到数据库中以防万一ConnectSuccess失败,但是该remove方法找不到实体(因为还没有进入数据库),并且在返回ReturnCodes.REQUESTABORT实体后保存。如何取消保存?

4

1 回答 1

0

通常,在这种情况下,您会执行 setRollbackOnly()。

您也可以抛出一个异常,该异常将仅触发回滚。

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

顺便说一句,在您的代码中执行此操作:

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

太宽泛,会阻止回滚功能。

于 2012-08-03T13:19:01.650 回答