How to Set the Schema Name Dynamically in Spring JPA
Learn how to dynamically provide the JPA schema name in a Spring Boot application with Postgres and MySQL examples
Imagine multiple entities sharing the same database but using different schemas. The requirement is that the schema name should change based on the deployment environments. For example, SCHEMA_DEV
, SCHEMA_TEST
, SCHEMA_PROD
.
You might think, “Can I just grab the schema value from the application properties using the schema
property in my entity class?” For instance:
@Entity
@Table(name = "Entity1", schema="SCHEMA1_$({env})")
Unfortunately, Spring Boot will not resolve the property value ”${env}”
.
There are multiple approaches to solve this problem. For example, using multiple data source connections or implementing Hibernate’s multi-tenancy. Using these methods means you’ll need to do extra coding and configuration, which can lead to potential problems.
In this tutorial, you’ll see a simple solution that requires just a few lines of code. You can apply this solution to any entity during application startup.
Let’s dive in!