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

时间:2014-10-09 22:25:05

标签: 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();
    }
...

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

1 个答案:

答案 0 :(得分: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());
        }
    };
}

如果你正在使用Java 8,你可以使用lambdas简化InitializingBean到这个表单的定义:

@Bean
public InitializingBean populatorExecutor() {
    return () -> DatabasePopulatorUtils.execute(databasePopulator(), dataSource());
}

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

希望此解决方案适合您