Hibernate @Table批注中的动态架构 [英] Dynamic schema in Hibernate @Table Annotation

查看:261
本文介绍了Hibernate @Table批注中的动态架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在两个环境中有四个MySQL数据库架构:

Imagine you have four MySQL database schemas across two environments:

  • foo(产品数据库)
  • bar(foo数据库的正在进行的重组),
  • foo_beta(测试数据库)
  • bar_beta(新结构的测试数据库).
  • foo (the prod db),
  • bar (the in-progress restructuring of the foo db),
  • foo_beta (the test db),
  • and bar_beta (the test db for new structures).

进一步,假设您有一个Spring Boot应用程序,该应用程序在实体上带有Hibernate批注,如下所示:

Further, imagine you have a Spring Boot app with Hibernate annotations on the entities, like so:

@Table(name="customer", schema="bar")
public class Customer { ... }

@Table(name="customer", schema="foo")
public class LegacyCustomer { ... }

在本地开发时没问题.您可以在本地环境中模拟生产数据库表名称.但是,然后您尝试在功能上线之前对其进行演示,并希望将其上载到服务器.您在另一个端口上启动了该应用程序的另一个实例,并意识到此副本需要指向"foo_beta"和"bar_beta",而不是"foo"和"bar"!该怎么办!

When developing locally it's no problem. You mimic the production database table names in your local environment. But then you try to demo functionality before it goes live and want to upload it to the server. You start another instance of the app on another port and realize this copy needs to point to "foo_beta" and "bar_beta", not "foo" and "bar"! What to do!

如果您仅在应用程序中使用一种架构,则可以完全省略该架构并指定hibernate.default_schema,但是...您正在使用两种.这样就可以了.

Were you using only one schema in your app, you could've left off the schema all-together and specified hibernate.default_schema, but... you're using two. So that's out.

Spring EL -例如@Table(name="customer", schema="${myApp.schemaName}")不是一个选项-(甚至带有一些愚蠢的没人需要此"注释),因此,如果动态定义模式是荒谬的,那么该怎么办?除了,您知道,首先不要陷入这种可笑的情况.

Spring EL--e.g. @Table(name="customer", schema="${myApp.schemaName}") isn't an option--(with even some snooty "no-one needs this" comments), so if dynamically defining schemas is absurd, what does one do? Other than, you know, not getting into this ridiculous scenario in the first place.

推荐答案

您可以尝试使用拦截器

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();  

所以发生的事情是,一旦执行onPrepareStatement,就会调用此代码块,并且模式名称将从模式更改为schema1.

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.

这篇关于Hibernate @Table批注中的动态架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆