如何在 Spring 启动时加载 sql 函数?

How to load a sql function on startup with Spring?

我正在为我的应用程序使用 Spring-Boothibernate.hbm2ddl.=update

如何确保在启动时执行 sql 脚本? 因此,我想确保 FUNCTION .. LANGUAGE plpgsql 存在于我的 postgresql 数据库中。

通过使用XML

<jdbc:initialize-database data-source="dataSource">
  <jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>
  <jdbc:script location="classpath:com/foo/sql/db-test-data.sql"/>
</jdbc:initialize-database>

通过使用注释(下面的例子应该放在你的@Configurationclass中)

@Value("classpath:com/foo/sql/db-schema.sql")
private Resource schemaScript;

@Value("classpath:com/foo/sql/db-test-data.sql")
private Resource dataScript;

@Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
    final DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);
    initializer.setDatabasePopulator(databasePopulator());
    return initializer;
}

private DatabasePopulator databasePopulator() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(schemaScript);
    populator.addScript(dataScript);
    return populator;
}