我已經研究了好幾個小時了,但當我將實體保存在封裝事務中時,我找不到一種方法來繞過 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);}
1 回答

吃雞游戲
TA貢獻1829條經驗 獲得超7個贊
MySQL 歷史上默認使用 MyISAM 引擎創建表,該引擎不支持事務。后來添加了 InnoDB,它確實支持事務,但是 MyISAM 在相當長的一段時間內仍然是默認值。
Hibernate 及其方言遵循相同的默認值,因此 MySQL 方言的默認值是 MyISAM(為了向后兼容)。
有兩種方法可以解決此問題:選擇特定方言或使用特定屬性從 MyISAM 切換到 InnoDB。
要選擇方言,請使用spring.jpa.database-platform
來指定所需的依賴項。
spring.jpa.database-platform=org.hibernate.dialect.MySQL57InnoDBDialect`
或設置屬性使用
spring.jpa.properties.hibernate.dialect.storage_engine=innodb
或兩者的組合(因為MySQL57InnoDBDialect
現在已棄用該hibernate.dialect.storage_engine
屬性)。
spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect spring.jpa.properties.hibernate.dialect.storage_engine=innodb
添加回答
舉報
0/150
提交
取消