简体   繁体   中英

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. I can't keep this function inside my postgres database as i want to maintain at application level. I tried to use schema.sql (from resources folder) and this looks like executing during server startup only.

However i want to call this plsql block everytime when needed through JPA or JDBCTemplate.

Any alternative other than schema.sql which can execute on-demand?

In unit tests there is @Sql annotation, that you can use to execute a script:

@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 )

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

@Autowired
JdbcTemplate jdbcTemplate;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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