- Postgresql multi tenant support
- Oracle multi tenant support
<dependency>
<groupId>br.com.zup</groupId>
<artifactId>spring-tenant</artifactId>
<version>VERSION</version>
</dependency>
Define a prefix for your tenants and add in your spring application.properties:
tenant.prefix=my_prefix
Supported without any special configuration.
It's necessary to define the default tenant in your spring application.properties:
tenant.default=some_user
This project has dependency to spring-jdbc, and the beans dataSource and jdbcTemplate needs to be provided by your spring application.
@Configuration
@Import(TenantConfig.class) // import tenant configuration
public class YourAppConfig {
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) { // it depends on a dataSource
return new JdbcTemplate(dataSource);
}
}
Set the database profile via java args:
postgresql:
-Dspring.profiles.active=postgresql
oracle:
-Dspring.profiles.active=oracle
Snippet code to get all tenants by a particular prefix
@Value("${tenant.prefix}")
private String tenantPrefix;
@Autowired
private TenantDiscoverer tenantDiscoverer;
Optional<List<Tenant>> tenants = tenantDiscoverer.getTenants(tenantPrefix);
The main component of solution, it's responsible for intercept all connections from javax.sql.DataSource.getConnection and execute the alter session based from tenant in your context (thread local). By default this component is already configured.
String tenant = getTenant();// get tenant from request (e.g. Header) or database (e.g. TenantDiscoverer)
TenantContextHolder.set(tenant);
// run some code to access your database...
// all database operations are run in your tenant session also prepared by component TenantConnectionPrepareAspect.
- Support more database (e.g. MySQL, SQLServer, DB2, Sybase, Firebird, etc)