ebean icon indicating copy to clipboard operation
ebean copied to clipboard

Q: Is it possible to change entity table?

Open vnnv opened this issue 1 year ago • 5 comments

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") ?

vnnv avatar Oct 20 '24 18:10 vnnv

Yes .setBaseTable("schema.table") does already exist.

You can do exactly Db.find(Entity.class).setBaseTable("schema.table") indeed.

rbygrave avatar Oct 20 '24 18:10 rbygrave

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".

vnnv avatar Oct 20 '24 18:10 vnnv

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.

rbygrave avatar Oct 20 '24 19:10 rbygrave

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

vnnv avatar Oct 20 '24 19:10 vnnv

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;
    }

rbygrave avatar Oct 20 '24 20:10 rbygrave

Thank you Rob, I'll dig in this :)

vnnv avatar Oct 21 '24 05:10 vnnv

Ok, lets close this for now - reopen if we need it.

rbygrave avatar Oct 22 '24 06:10 rbygrave