Q: Is it possible to change entity table?
Usually in my projects I use @Table(schema = "schema_name", name = "table_name") to mark where the entity must be persisted.
But now I am in a project that schema and/or table name must come from a configuration. A single code base must connect with different credentials and access different schema/table (with the same structure).
So my question is is it possible runtime to change table/schema of an entity? Something similar like using Db.find(Entity.class).setBaseTable("schema.table") ?
Yes .setBaseTable("schema.table") does already exist.
You can do exactly Db.find(Entity.class).setBaseTable("schema.table") indeed.
Yes, this is if I want to query result. But my case is to set the schema for the save.
Something like Db.save(GivenEntity).setBaseTable("schema.table").doSave(); and the result to be persisted in the "schema.table".
Dynamically changing the schema is supported (via the underlying java.sql.Connection). That is, if the table name doesn't change but schema does that can be done.
But if the table name changes, then no, there is no provision to change the table name dynamically.
Thanks for the info.
Ok, is the correct way something like this:
Transaction transaction = Db.createTransaction(); transaction.connection().setSchema("new-schema"); Db.save(entity, transaction);
Yes. This is pretty much what the schema based Multi-Tenant option does.
Refer: class MultiTenantDbSchemaSupplier implements DataSourceSupplier
Refer: private static class SchemaDataSource implements DataSource
/**
* Return the connection where tenantId is optionally provided by a lazy loading query.
*/
Connection getConnectionForTenant(Object tenantId) throws SQLException {
Connection connection = dataSource.getConnection();
connection.setSchema(schemaProvider.schema(tenantId));
return connection;
}
Thank you Rob, I'll dig in this :)
Ok, lets close this for now - reopen if we need it.