1 package com.supwisdom.multitenant.datasource;
3 import com.supwisdom.multitenant.TenantContextHolder;
4 import com.supwisdom.multitenant.TenantDetails;
5 import lombok.extern.slf4j.Slf4j;
6 import org.hibernate.HibernateException;
7 import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
8 import org.springframework.stereotype.Component;
10 import javax.sql.DataSource;
11 import java.sql.Connection;
12 import java.sql.SQLException;
15 * Created by shuwei on 2018/12/4.
19 public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider {
20 private final DataSource dataSource;
22 private final MultiTenantDataSourceProvider dsProvider;
24 public MultiTenantConnectionProviderImpl(DataSource dataSource,
25 MultiTenantDataSourceProvider provider) {
26 this.dataSource = dataSource;
27 this.dsProvider = provider;
31 public Connection getAnyConnection() throws SQLException {
32 return dataSource.getConnection();
36 public void releaseAnyConnection(Connection connection) throws SQLException {
41 public Connection getConnection(String ti) throws SQLException {
42 TenantDetails tenant = TenantContextHolder.getContext().getTenant();
43 final Connection connection = getAnyConnection();
46 log.debug("postgresql set search path to <" + tenant.getDbSchema() + ">");
47 connection.createStatement().execute(dsProvider.getTenantSQL(tenant));
49 log.debug("postgresql set search path to public");
50 connection.createStatement().execute(dsProvider.getDefaultSQL());
52 } catch (SQLException e) {
53 assert tenant != null;
54 throw new HibernateException("Problem setting schema to " + tenant.toString(), e);
60 public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
65 public boolean supportsAggressiveRelease() {
69 @SuppressWarnings("rawtypes")
71 public boolean isUnwrappableAs(Class unwrapType) {
76 public <T> T unwrap(Class<T> unwrapType) {