Dynamic schema in Hibernate @Table Annotation

前端 未结 3 2004
孤街浪徒
孤街浪徒 2021-01-05 13:27

Imagine you have four MySQL database schemas across two environments:

  • foo (the prod db),
  • bar (the in-progress restructuring
相关标签:
3条回答
  • 2021-01-05 13:34

    I have fixed such kind of problem by adding support for my own schema annotation to Hibernate. It is not very hard to implement by extending LocalSessionFactoryBean (or AnnotationSessionFactoryBean for Hibernate 3). The annotation looks like this

    @Target(TYPE)
    @Retention(RUNTIME)
    public @interface Schema {
    
        String alias() default "";
    
        String group() default "";
    
    }
    

    Example of using

    @Entity
    @Table
    @Schema(alias = "em", group = "ref")
    public class SomePersistent {
    
    }
    

    And a schema name for every combination of alias and group is specified in a spring configuration.

    0 讨论(0)
  • 2021-01-05 13:50

    you can try with interceptors

    public class CustomInterceptor extends EmptyInterceptor {
    @Override
        public String onPrepareStatement(String sql) {
              String prepedStatement = super.onPrepareStatement(sql);
              prepedStatement = prepedStatement.replaceAll("schema", "Schema1");
              return prepedStatement;
        }
    }
    

    add this interceptor in session object as

    Session session = sessionFactory.withOptions().interceptor(new MyInterceptor()).openSession();  
    

    so what happens is when ever onPrepareStatement is executed this block of code will be called and schema name will be changed from schema to schema1.

    0 讨论(0)
  • 2021-01-05 13:54

    You can override the settings you declare in the annotations using a orm.xml file. Configure maven or whatever you use to generate your deployable build artifacts to create that override file for the test environment.

    0 讨论(0)
提交回复
热议问题