Where to place init.sql file for a java application

Viewed 127

Currently we have the following project structure:

root
|_____ api
|_____ common
      |______ repository
              |_______ src
                       |_____ main
                              |_______ kotlin
                              |_______ sql
                                       |____ init.sql
                       |_____ test
                              |_______ kotlin
                                       |_______ ...
                                                |____ Test.kt
              |_______ build.gradle.kts
      |______ test-utils
              |_________ src
                         |_______...
                                 |_____ package
                                        |________ TestDataSourceConfiguration.kt
      |______ ...
|_____ runner
       |______ src
               |_____ test
                      |______ ...
                              |____ TestRunner.kt  

TestDataSourceConfiguration.kt creates connection to h2 database with init script from init.sql.

@TestConfiguration
@PropertySource("classpath:database-test.properties")
open class TestDataSourceConfiguration(
    @Autowired private val environment: Environment,
) {
   @Bean
   open fun dataSource(): DataSource {
        .... 
        val url = "jdbc:h2://~test;INIT=RUNSCRIPT FROM 'src/main/sql/init.sql'"
        ....
   }

So this works good in Test.kt, but when run tests from TestRunner.kt it fails, because user.dir points to root/runner and init.sql can't be found

I was trying to set for all subprojects new property which points to the root directory of a rootProject... but no avail

Any thoughts how to do this properly?

1 Answers

You can create a data.sql file in your src/main/resources folder and it will be automatically executed on startup.

You can also create a schema.sql to init your database schema if hibernate don’t.

If you still want to specify the runscript you can put it in src/main/resources and do the following : RUNSCRIPT FROM 'classpath:init.sql'

Related