jpa - 如果发生异常,则回滚所有插入
问题描述
我正在尝试将多个实体持久化到数据库中。但是如果其中一个插入遇到异常,我需要回滚所有插入。我怎样才能做到这一点?这是我所做的:
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 方法?
解决方案
推荐阅读
- java - 如何在 C#/Xamarin 中使用带有来自 android 钥匙串的私钥的 X.509 证书?
- python - 替换 python 中的 \G 锚点
- javascript - 从服务器发送 2 组不同的错误消息
- encryption - 如何使用 Yubikey 签署任意数据
- performance - 使用 JProfiler 监控生产中的应用程序
- python - 多处理引发操作系统错误,但仍然给出结果?
- python - TensorFlow Keras CuDNNGRU 到 GRU 的转换
- excel-formula - Excel - 累积季度储蓄分月
- java - 如何使用选定的微调器值进行计算?
- accessibility - 为什么在文本编辑器 div 中突出显示多行时 JAWS 屏幕阅读器重复行?