亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JPA 保存多個實體,在 Spring @Transactional 內部并啟用

JPA 保存多個實體,在 Spring @Transactional 內部并啟用

慕森王 2023-07-28 10:42:47
我已經研究了好幾個小時了,但當我將實體保存在封裝事務中時,我找不到一種方法來繞過 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
查看完整回答
反對 回復 2023-07-28
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號