Skip to content

How to run schema creation SQL statements before context initialization? #275

@soid

Description

@soid

I'm trying to use @Sql annotation for initializing the db schema like this:
@Sql(scripts = ["/schema.sql"])
(the code is in Kotlin here)

But it seems it is only executed after spring context in initialized. So, if my components rely on loading the db in initialization then it fails. For example, if I want to use the db in @PostConstruct method of my component:

@Component
class MyService(val personRepository: PersonRepository) {
    @PostConstruct
    fun init() {
        val persons = personRepository.findAll()
        println("Counted persons: " + persons.count())
    }
    ...

then it fails during Spring context initialization due to missing table. This is because schema.sql is only executed after the initialization.

I also tried to no avail:

  • specifying the executionPhase: @Sql(scripts = ["/schema.sql"], executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)
  • use InitializingBean.afterPropertiesSet instead of @PostConstruct for component initialization
  • use spring.jpa.defer-datasource-initialization=true in properties (link)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions