数据库构建后运行数据脚本

jen*_*gar 3 java spring hibernate jpa eclipselink

所以我很惊讶这个问题的答案并不容易找到,但是我希望在数据库生成后插入一些数据.

RootConfig.java:

...
    @Bean
    public DataSource dataSource() throws SQLException {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.HSQL)
                .setName("db")
                .addScript("setup_data.sql")
                .continueOnError(true)
                .build();
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() throws SQLException {


        EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(true);
        vendorAdapter.setDatabase(Database.HSQL);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        Map<String, Object> props = new HashMap<>();
        props.put("eclipselink.weaving", "false");
        props.put("eclipselink.target-database", HSQLPlatform.class.getName());
        props.put("eclipselink.cache.shared.default", "false");
        props.put("eclipselink.logging.parameters", "true");
        props.put("eclipselink.logging.level", "FINEST");
        props.put("eclipselink.logging.level.sql", "FINEST");
        props.put("eclipselink.logging.level.cache", "FINEST");

        factory.setJpaPropertyMap(props);

        factory.setPackagesToScan("com.citysports.leaguesports.domain");
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();

        return factory.getObject();
    }
...
Run Code Online (Sandbox Code Playgroud)

我正在生成ddl,但是当我addScript('setup_data.sql')收到错误时,因为它还没有生成表.如何在ddl生成后运行脚本?

Boh*_*rdt 7

你可以用DatabasePopulator.为此,请将以下bean定义放在配置类中.

@Bean
public ResourceDatabasePopulator databasePopulator() {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding("UTF-8");
    populator.addScript(new ClassPathResource("setup_data.sql"));
    return populator;
}

@Bean
public InitializingBean populatorExecutor() {
    return new InitializingBean() {
        @Override
        public void afterPropertiesSet() throws Exception {
            DatabasePopulatorUtils.execute(databasePopulator(), dataSource());
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Java 8,则可以InitializingBean使用lambdas 将定义简化为此表单:

@Bean
public InitializingBean populatorExecutor() {
    return () -> DatabasePopulatorUtils.execute(databasePopulator(), dataSource());
}
Run Code Online (Sandbox Code Playgroud)

基本上,您定义了一个包含要执行的脚本的populator,并InitializingBean在数据源bean准备就绪时负责运行这些脚本.

希望这个解决方案适合您