Is it possible to dynamically display the table name for a domain object in a graph?

I have a domain that looks something like

class Foo { String name static mapping = { table 'foo' } } 

but I want to do more:

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

What I want to know is this possible?

Thanks!

+4
source share
2 answers

It is possible. You can add a Hibernate interceptor to process all SQL statements and parse / replace some token in the table name that you enter when matching with the actual table name that 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) } 
+7
source

I do not think that's possible. When the application starts, the closure of the mapping calculated, and the result is a Hibernate mapping. This happens once at startup, so dynamic resolution will not happen.

Something comparable in the multi-tenant-core plugin, using the "one tenant" setting, you have a separate database for each tenant.

+1
source

Source: https://habr.com/ru/post/989504/


All Articles