jpa臟檢查在@SpringBootApplication中不起作用
我像這樣在@SpringBootApplication 中使用initDb
@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
@RequiredArgsConstructor
public class main {
private final PoiRepository poiRepository;
private final PoiCategoryRepository poiCategoryRepository;
public static void main(String[] args) {
SpringApplication.run(main.class, args);
}
//Dummy data poiCategory
@Bean
@Profile("local")
@Transactional
public CommandLineRunner createPoiCategory(PoiCategoryRepository repository) {
return args -> {
if (repository.findAll().size() == 0) {
PoiCategory parent = repository.save(PoiCategory.builder()
.name("parent")
.imageFileName("test")
.build());
PoiCategory child = repository.save(PoiCategory.builder()
.name("child")
.imageFileName("test2")
.build());
parent.addChildCategory(child);
System.out.println("parent = " parent);
parent.setImageFileName("1234");
System.out.println("parent.getImageFileName() = " parent.getImageFileName());
}
};
}
}
parent.addChildCategory(parent) 和 parent.setImageFileName("1234") 沒有改變
但如果我使用
repository.save(parent);
repository.save(child);
然后父母和孩子將更新
為什么 jpa 的臟檢查和更新不起作用?
uj5u.com熱心網友回復:
這是因為@Tranasctional如果在方法上宣告它不起作用@Bean。它應該在您要執行的實際方法上進行注釋。因此,您的代碼現在實際上不會包含任何事務,CommandLineRunner#run()并且只有在事務中修改了物體時,臟檢查才有效。
更改為以下內容應該可以解決您的問題:
public class MyCommandLineRunner implements CommandLineRunner {
private PoiCategoryRepository poiCategoryRepository;
public MyCommandLineRunner(PoiCategoryRepository poiCategoryRepository) {
this.poiCategoryRepository = poiCategoryRepository;
}
@Transactional
@Override
public void run(String... args) throws Exception {
// put your codes that you want to execute within a transaction here....
}
}
并定義MyCommandLineRunnerbean:
@Bean
public MyCommandLineRunner myCommandLineRunner(PoiCategoryRepository poiCategoryRepository) {
return new MyCommandLineRunner(poiCategoryRepository);
}
如果您呼叫它,它將立即更新父級和子級save(),JpaRepository因為實作已經@Tranasctional在此方法上進行了注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/514376.html
標籤:爪哇春天弹簧靴休眠jpa
上一篇:啟用/禁用SpringBoot應用程式的所有控制器?
下一篇:SpringJPA異步保存
