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

霸气de小男生 提交于 2019-11-27 15:36:45

问题


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!


回答1:


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.

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:

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



回答2:


I don't think that's possible. Upon application startup, the mapping closure is evaluated and Hibernate mapping are generated as a result. 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.



来源:https://stackoverflow.com/questions/5424148/is-it-possible-to-map-a-table-name-for-a-domain-object-dynamically-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!