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

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

最好以创建实体并使它们通过Repository接口持久化的形式,而不是编写简单的SQL代码。像RoR的Rake db:seed助手一样。

如果在所有的Bean都已经注入并且数据库准备就绪时,框架公开了执行任务的钩子,那么它也可以工作。

回答:

您可以捕获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(...));

}

}

或者甚至像在您的Application(或其他“ config”)类中的Bean一样实现它们:

@SpringBoot" title="SpringBoot">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在启动时将示例数据插入数据库 的全部内容, 来源链接: utcz.com/qa/429612.html

回到顶部