Fernando Frazão
Fernando Frazão

Reputation: 25

Spring Boot and Hibernate: Start an application even if a connection to the database is not available

My Spring Boot application needs to connect to two different databases. The first database (main) is installed on the same server as the localhost application and the other database (secondary) on a remote server and that is not always available (for maintenance, backup, testing, etc.).

I use the following configuration (application.properties).

# main connection
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/?autoReconnect=true&verifyServerCertificate=false&useSSL=false&requireSSL=false
spring.datasource.username=emater
spring.datasource.password=emater

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# secondary connection
planejamento.datasource.driverClassName=com.mysql.jdbc.Driver
planejamento.datasource.url=jdbc:mysql://10.22.1.4/?verifyServerCertificate=false&useSSL=false&requireSSL=false
planejamento.datasource.username=emater
planejamento.datasource.password=emater
planejamento.datasource.testWhileIdle = false

#config hibernate
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQLSpatial56Dialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
spring.jpa.show-sql=true
spring.jpa.format-sql=true
spring.jpa.use-sql-comments=true
spring.jpa.hibernate.enable_lazy_load_no_trans=true

When initializing the application hibernate tries to connect to both databases. If the second database is not available at the time, an exception is thrown and application initialization is aborted.

Is there any property I could use to prevent my application from aborting at the time of its startup?

What should I do?

Upvotes: 2

Views: 3031

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153730

Hibernate requires to connect to the DB when the SessionFactory so that i can extract the DatabaseMetaData from a DB Connection.

With the DatabaseMetaData, it needs to find out:

  • the current catalog and schema
  • how to qualify identifiers
  • if the DB supports temporary tables
  • if the DDL causes Transaction commit
  • if the Driver supports scrollable ResultSet
  • if the Driver supports batch updates
  • if the Driver return generated keys for IDENTITY columns

This info is resolved when the SessionFactory is initialized, so you are better off starting a new MicroService lazily, when the associated database is avilable as well.

Upvotes: 3

Related Questions