737cba0dade87a65ee5b00786e0afed2ac2d81fe
[epayment/food_payapi.git] /
1 package com.supwisdom.multitenant.datasource;
2
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;
9
10 import javax.sql.DataSource;
11 import java.sql.Connection;
12 import java.sql.SQLException;
13
14 /**
15  * Created by shuwei on 2018/12/4.
16  */
17 @Slf4j
18 @Component
19 public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider {
20   private final DataSource dataSource;
21
22   private final MultiTenantDataSourceProvider dsProvider;
23
24   public MultiTenantConnectionProviderImpl(DataSource dataSource,
25                                            MultiTenantDataSourceProvider provider) {
26     this.dataSource = dataSource;
27     this.dsProvider = provider;
28   }
29
30   @Override
31   public Connection getAnyConnection() throws SQLException {
32     return dataSource.getConnection();
33   }
34
35   @Override
36   public void releaseAnyConnection(Connection connection) throws SQLException {
37     connection.close();
38   }
39
40   @Override
41   public Connection getConnection(String ti) throws SQLException {
42     TenantDetails tenant = TenantContextHolder.getContext().getTenant();
43     final Connection connection = getAnyConnection();
44     try {
45       if (tenant != null) {
46         log.debug("postgresql set search path to  <" + tenant.getDbSchema() + ">");
47         connection.createStatement().execute(dsProvider.getTenantSQL(tenant));
48       } else {
49         log.debug("postgresql set search path to public");
50         connection.createStatement().execute(dsProvider.getDefaultSQL());
51       }
52     } catch (SQLException e) {
53       assert tenant != null;
54       throw new HibernateException("Problem setting schema to " + tenant.toString(), e);
55     }
56     return connection;
57   }
58
59   @Override
60   public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
61     connection.close();
62   }
63
64   @Override
65   public boolean supportsAggressiveRelease() {
66     return false;
67   }
68
69   @SuppressWarnings("rawtypes")
70   @Override
71   public boolean isUnwrappableAs(Class unwrapType) {
72     return false;
73   }
74
75   @Override
76   public <T> T unwrap(Class<T> unwrapType) {
77     return null;
78   }
79 }