Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Table annotation and the need set catalog or schemas for development or deployment

Here's my problem.

When I'm developing I usually have a persistence class configured to H2 with @Profile("development") mapped to a local database on my computer. At the same time, I have another persistence class mapping the same entities, which is basically a copy of the first one, only configured to MySQL. These persistence classes are picked up by Spring depending on the @Profile annotation, the second one is annotated with @Profile("default")

My problem is that when I deploy the @Profile("default") is picked up and MySQL needs the @Table annotation to be like this:

@Table(name = "tableName", catalog = "databaseName")

While on development, H2 understands only this:

@Table(name = "tableName", schema = "databaseName")

Is there a way to solve this problem? Some conditional way to switch the @Table annotation from schema to catalog on deployment?

like image 396
Marcelus Trojahn Avatar asked Nov 26 '25 23:11

Marcelus Trojahn


1 Answers

To achieve the desired behavior in Spring, conditional bean configuration and conditional annotations can be used.

 @Configuration
    public class EntityConfiguration {
    
        @Profile("development")
        static class H2Configuration {
            @Bean
            public JpaRepository<H2Entity, Long> h2Repository() {
                return new JpaRepository<H2Entity, Long>();
            }
        }
    
        @Profile("default")
        static class MySQLConfiguration {
            @Bean
            public JpaRepository<MySQLEntity, Long> mysqlRepository() {
                return new JpaRepository<MySQLEntity, Long>();
            }
        }
    }

In this configuration, the active Spring profile will be used for identifying the correct entity class and database environments.I hope this will work

like image 166
Taxhi Avatar answered Nov 29 '25 13:11

Taxhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!