简体   繁体   English

如何从spring-boot执行postgres sql块

[英]How to execute postgres sql block from spring-boot

I have to execute a block of sql script (typically a function) from spring boot application. 我必须从spring启动应用程序执行一个sql脚本块(通常是一个函数)。 I can't keep this function inside my postgres database as i want to maintain at application level. 我不能将此功能保留在我的postgres数据库中,因为我想在应用程序级别维护。 I tried to use schema.sql (from resources folder) and this looks like executing during server startup only. 我尝试使用schema.sql (来自资源文件夹),这看起来像只在服务器启动期间执行。

However i want to call this plsql block everytime when needed through JPA or JDBCTemplate. 但是我想在每次需要时通过JPA或JDBCTemplate调用这个plsql块。

Any alternative other than schema.sql which can execute on-demand? schema.sql除了可以按需执行之外的任何其他选择吗?

In unit tests there is @Sql annotation, that you can use to execute a script: 在单元测试中有@Sql注释,您可以使用它来执行脚本:

@RunWith(SpringRunner.class)
@SpringBootTest
@Sql("/reset_sequences.sql")
public class ModuleTemplateRepositoryTests { ... }

For launching custom sql script from spring application we were using ScriptUtils (stackoverflow here ) 为了从spring应用程序启动自定义sql脚本,我们使用ScriptUtils此处为stackoverflow)

@Value("classpath:reset_sequences.sql")
Resource script;

@Autowired
JdbcTemplate jdbcTemplate;

...
ScriptUtils.executeSqlScript(
    jdbcTemplate.getDataSource().getConnection(), script);

如果您将函数存储在数据库中,则可以在此处查看此示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM