gpt4 book ai didi

spring-boot - Spring Boot 在启动时将示例数据插入数据库

转载 作者:行者123 更新时间:2023-12-04 01:24:40 25 4
gpt4 key购买 nike

在服务器启动时创建测试数据并将它们插入数据库的正确方法是什么(我使用的是 JPA/JDBC 支持的 Postgres 实例)。

最好是创建实体并让它们通过存储库接口(interface)持久化,而不是编写普通的 SQL 代码。类似于 RoR 的 Rake db:seed helper 。

如果框架在所有 bean 都被注入(inject)并且数据库准备好时暴露了一个钩子(Hook)来做一些事情,那也可以工作。

最佳答案

你可以抓到ApplicationReadyEvent然后插入演示数据,例如:

@Component
public class DemoData {

@Autowired
private final EntityRepository repo;

@EventListener
public void appReady(ApplicationReadyEvent event) {

repo.save(new Entity(...));
}
}

或者你可以实现 CommandLineRunnerApplicationRunner , 在应用程序完全启动时加载演示数据:

@Component
public class DemoData implements CommandLineRunner {

@Autowired
private final EntityRepository repo;

@Override
public void run(String...args) throws Exception {

repo.save(new Entity(...));
}
}

@Component
public class DemoData implements ApplicationRunner {

@Autowired
private final EntityRepository repo;

@Override
public void run(ApplicationArguments args) throws Exception {

repo.save(new Entity(...));
}
}

甚至可以在您的应用程序(或其他“配置”)类中像 Bean 一样实现它们:

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Bean
public CommandLineRunner demoData(EntityRepository repo) {
return args -> {

repo.save(new Entity(...));
}
}
}

关于spring-boot - Spring Boot 在启动时将示例数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com