简体   繁体   English

是否可以在grails中动态映射域对象的表名?

[英]Is it possible to map a table name for a domain object dynamically in grails?

I have a domain that looks something like 我有一个看起来像的域名

class Foo {

  String name

  static mapping = {
     table 'foo'    
  }
}

but I want to make is more like : 但我想做的更像是:

static mapping = {
   table "foo_${dynamicVarThatComesFromRequest}"
}

What I want to know is whether this is even possible? 我想知道的是这是否可能?

Thanks! 谢谢!

It is possible. 有可能的。 You can add a Hibernate interceptor to process all SQL statements and parse/replace some token in the table name you enter in the mapping with the actual table name you want to use. 您可以添加一个Hibernate拦截器来处理所有SQL语句,并解析/替换您在映射中输入的表名中的一些标记,其中包含您要使用的实际表名。

src/groovy/DynamicTableNameInterceptor.groovy : src / groovy / DynamicTableNameInterceptor.groovy:

import org.hibernate.EmptyInterceptor

public class DynamicTableNameInterceptor extends EmptyInterceptor {

    public String onPrepareStatement(String sql) {
         // some kind of replacement logic here
         def schema=SomeHelperClass.resolveSchema()
         return sql.replaceAll('_SCHEMA_', schema) 
    }

}

grails-app/conf/spring/resources.groovy: 的grails-app / CONF /弹簧/ resources.groovy:

beans = {
    // This is for Grails 1.3.x , in previous versions, the bean name is eventTriggeringInterceptor
    entityInterceptor(DynamicTableNameInterceptor)
}

I don't think that's possible. 我不认为这是可能的。 Upon application startup, the mapping closure is evaluated and Hibernate mapping are generated as a result. 应用程序启动时,将评估mapping闭包,并生成Hibernate映射。 This happens once upon startup, so dynamic resolution will not occur. 这在启动时发生一次 ,因此不会发生动态分辨率。

Something comparable is done in the multi-tenant-core plugin, using the 'single tenant' setup, you have a seperate database for each tenant. 多租户核心插件中进行了类似的操作,使用“单租户”设置,每个租户都有一个单独的数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM