首页 > 解决方案 > 如果发生异常,则回滚所有插入

问题描述

我正在尝试将多个实体持久化到数据库中。但是如果其中一个插入遇到异常,我需要回滚所有插入。我怎样才能做到这一点?这是我所做的:

public class RoleCreationApplyService extends AbstractEntityProxy implements EntityProxy {


    @Inject
    @Override
    public void setEntityManager(EntityManager em) {
        super.entityManager = em;
    }

    @Resource
   UserTransaction utx;
 public Object acceptAppliedRole(String applyId, Role parentRole, SecurityContext securityContext) throws Exception {
        utx.begin();
        try {
            FilterWrapper filter = FilterWrapper.createWrapperWithFilter("id", Filter.Operator._EQUAL, applyId);
            RoleCreationApply roleCreationApply = (RoleCreationApply) getByFilter(RoleCreationApply.class, filter);
            Role appliedRole = new Role();
            appliedRole.setRoleUniqueName(roleCreationApply.getRoleName());
            appliedRole.setRoleName(roleCreationApply.getRoleName());
            appliedRole.setRoleDescription(roleCreationApply.getRoleDescription());
            appliedRole.setRoleDisplayName(roleCreationApply.getRoleDisplayName());
            appliedRole.setCreationTime(new Date());
            appliedRole.setCreatedBy(securityContext.getUserPrincipal().getName());
            Role childRole = (Role) save(appliedRole);
            parentRole.setCreationTime(new Date());
            parentRole.setCreatedBy(securityContext.getUserPrincipal().getName());
            parentRole = (Role) save(parentRole);
            RoleRelation roleRelation = new RoleRelation();
            roleRelation.setParentRole(parentRole);
            roleRelation.setChildRole(childRole);
            RoleRelation savedRoleRelation = (RoleRelation) save(roleRelation);
            PostRoleRelation postRoleRelation = new PostRoleRelation();
            postRoleRelation.setPost(roleCreationApply.getPost());
            postRoleRelation.setRoleRelation(savedRoleRelation);
            ir.tamin.framework.domain.Resource result = save(postRoleRelation);
            utx.commit();
            return result;
        } catch (Exception e) {
            utx.rollback();
            throw new Exception(e.getMessage());
        }

    }
}

这是AbstractEntityProxy类中的保存方法:

@Override
    @ProxyMethod
    public Resource save(Resource clientObject) throws ProxyProcessingException {
        checkRelationShips((Entity) clientObject, Method.SAVE, OneToOne.class, ManyToOne.class);
        try {
            entityManager.persist(clientObject);
        } catch (PersistenceException e) {
            throw new ResourceAlreadyExistsException(e);
        }
        return clientObject;
    }

但是,例如,当发生异常Unique Constraint Violated并进入 catch 块时,当尝试执行utx.rollback()它时会抱怨transaction does not exist,因此某些实体将持续存在。但如果一个失败,我希望所有人都回滚。

PS:我不想使用普通的 JDBC。什么是 JPA 方法?

标签: jpaeclipselink

解决方案


推荐阅读