|
| 1 | +package com.baeldung.multitenancy; |
| 2 | + |
| 3 | +import org.hibernate.tool.hbm2ddl.SchemaExport; |
| 4 | +import com.baeldung.multitenancy.implementation; |
| 5 | +import javax.sql.DataSource; |
| 6 | +import java.io.IOException; |
| 7 | +import java.sql.Connection; |
| 8 | +import java.sql.SQLException; |
| 9 | +import java.util.Map; |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +@Configuration |
| 14 | +public class MTConfig { |
| 15 | + |
| 16 | + @Bean |
| 17 | + public SessionFactoryBean sessionFactory(Map<String, DataSource> dataSourceMap, DataSource dataSource){ |
| 18 | + |
| 19 | + SessionFactoryBean sf = new SessionFactoryBean(); |
| 20 | + sf.setDataSourceMap(dataSourceMap); |
| 21 | + sf.setDataSource(dataSource); |
| 22 | + |
| 23 | + try{ |
| 24 | + Properties prop = new Properties(); |
| 25 | + prop.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); |
| 26 | + prop.setProperty("hibernate.show_sql", "true"); |
| 27 | + prop.setProperty("hibernate.multiTenancy", "DATABASE"); |
| 28 | + prop.setProperty("hibernate.tenant_identifier_resolver", "currentSessionTenantIdentifierResolver"); |
| 29 | + prop.setProperty("hibernate.multi_tenant_connection_provider", "simpleMultiTenantConnectionProvider"); |
| 30 | + |
| 31 | + sf = new AnnotationConfiguration().setProperties(prop).configure().buildSessionFactory(); |
| 32 | + return sf; |
| 33 | + |
| 34 | + } catch (Throwable ex) { |
| 35 | + System.err.println("Failed to load the SessionFactory: " + ex); |
| 36 | + throw new ExceptionInInitializerError(ex); |
| 37 | + } |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + @Bean(name = "currentSessionTenantIdentifierResolver") |
| 42 | + @Scope("request", proxyMode = ScopedProxyMode.INTERFACES) |
| 43 | + public CurrentSessionTenantIdentifierResolver currentSessionTenantIdentifierResolver(){ |
| 44 | + |
| 45 | + CurrentSessionTenantIdentifierResolver cstir = new CurrentSessionTenantIdentifierResolver(); |
| 46 | + return cstir; |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + @Bean(name = "simpleMultiTenantConnectionProvider") |
| 51 | + public SimpleMultiTenantConnectionProvider simpleMultiTenantConnectionProvider(Map<String, DataSource> dataSourceMap){ |
| 52 | + |
| 53 | + SimpleMultiTenantConnectionProvider smtcp = new SimpleMultiTenantConnectionProvider(); |
| 54 | + smtcp.setDataSourceMap(dataSourceMap); |
| 55 | + return cstir; |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | +} |
0 commit comments