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

Dar*_*ius 10 spring-data-jpa spring-boot

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

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

如果框架在注入所有bean并且数据库准备就绪时公开了一个用于执行操作的挂钩,那么这也可以起作用.

Cep*_*pr0 25

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

@Component
public class DemoData {

    @Autowired
    private final EntityRepository repo;

    @EventListener
    public void appReady(ApplicationReadyEvent event) {

        repo.save(new Entity(...));
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以在应用程序完全启动时实现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(...));
    }
}
Run Code Online (Sandbox Code Playgroud)

甚至可以像你的应用程序(或其他'config')类中的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(...));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Mos*_*rad 8

来自 Spring 文档:http : //docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#howto-database-initialization

使用 Hibernate 初始化数据库如果 Hibernate 从头开始​​创建模式(即,如果 ddl-auto 属性设置为 create 或 create-drop),则将在启动时执行类路径根目录中 名为import.sql的文件。如果你小心的话,这对于演示和测试很有用,但可能不是你想要在生产中的类路径上的东西。它是一个 Hibernate 特性(与 Spring 无关)。