我已经研究了好几个小时了,但当我将实体保存在封装事务中时,我找不到一种方法来绕过 JPARepository 自动启动/提交事务的问题。
我总共创建了 3 个实体。前 2 个实体将被创建,以便在创建第三个实体时ClientAdmin,实体可以在持久化之前形成关系。CreditPotInstitution
当抛出异常时,我希望它能够使创建的实体不被提交(即整个过程回滚)。
目前,我可以在日志中看到 JPA Save 方法可能会启动自己的事务(我不完全理解日志),这会导致已调用的实体repo.save(entity)在自己的事务中提交?
任何帮助将不胜感激。
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public void createInstitution(InstitutionSignUpForm form) throws Exception {
//Create Admin account.
ClientAdmin clientAdmin = new ClientAdmin();
clientAdmin.setRole(roleRepo.findOneByRole("SUPER_ADMIN").orElseThrow(() -> new Exception("Can not resolve role SUPER_ADMIN")));
clientAdmin.setPassword(passwordEncoder.encode(form.getPassword()));
clientAdmin.setUsername(form.getUsername());
clientAdmin = clientAdminRepo.save(clientAdmin);
//Create Credit Pot for institution.
CreditPot creditPot = new CreditPot();
creditPot.setIsPrimaryPot(true);
creditPot.setName("Primary Credit Pot");
creditPot.setCredits(300L);
creditPot = creditPotRepo.save(creditPot);
System.out.println("Throwing Exception.");
if(1==1) throw new Exception("!!!", new Throwable("!!!"));
//Create institution and assign relationships.
Institution institution = new Institution();
institution.setDiceCode(dicewareGenerator.generateRandomPassword(6));
institution.setName(form.getInstitutionName());
institution.setPrimaryCreditPot(creditPot);
clientAdmin.setInstitution(institution);
institutionRepo.saveAndFlush(institution);
}
吃鸡游戏
相关分类