Spring Boot 在启动时将示例数据插入数据库 [英] Spring Boot insert sample data into database upon startup

查看:70
本文介绍了Spring Boot 在启动时将示例数据插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the right way for creating test data upon server startup and inserting them into the database (I'm using a JPA/JDBC backed Postgres instance).

最好以创建实体的形式并让它们通过存储库接口持久化,而不是编写简单的 SQL 代码.类似于 RoR 的 Rake db:seed 助手.

Preferably in form of creating Entities and having them persisted through a Repository interface rather than writing plain SQL code. Something like RoR's Rake db:seed helper.

如果框架在注入所有 bean 并且数据库准备就绪时公开一个钩子来执行某些操作,那也可以工作.

If the framework exposes a hook for doing stuff when all the beans have been injected and the database is ready, that could also work.

推荐答案

可以捕捉ApplicationReadyEvent然后插入演示数据,例如:

You can catch ApplicationReadyEvent then insert demo data, for example:

@Component
public class DemoData {

    @Autowired
    private final EntityRepository repo;

    @EventListener
    public void appReady(ApplicationReadyEvent event) {

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

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

Or you can implement CommandLineRunner or ApplicationRunner, to load demo data when an application is fully started:

@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 一样实现它们:

Or even implement them like a Bean right in your Application (or other 'config') class:

@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 在启动时将示例数据插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆