Alessandro
Alessandro

Reputation: 611

Dynamic schema selection for Spring Data JPA repositories with schema coming from database

as the title says, I have an application (Spring Boot) which must execute some queries on specified objects on a SQL Server database. Such database having a single catalog and multiple schemas, which must be selected based on a previous query and some command line parameters.

I cannot seem to implement a strategy which involves Hibernate multi-tenancy, as most of the tutorials and answers on this site deal with schema names coming from a web request or an external parameter, while I need a database connection before creating the main multi-tenant EntityManager. So, I switched to a custom DataSource which tries to change the connection's default schema (using ALTER USER... WITH DEFAULT_SCHEMA = ...). But this also fails because the logged-in user does not have permission to alter his own default schema.

So I'm at a loss of what to do. Any suggestions?

Upvotes: 0

Views: 5769

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81970

Just create an EntityManager(Factory) per schema and put them in a map to choose from.

If you don't know the schemas before hand you can create EntityManager(Factory)s as soon as you learn about a schema.

that you can configure an EntityManagerFactory programatically.

Upvotes: 3

Related Questions