小编典典

实现一个AbstractMultiTenantConnectionProvider

hibernate

我正在尝试使用hibernate多租户(从第16章开始)。

现在,我的 ExtendedStorageManager 使用此方法启动多租户会话:

public Session getClabSession(int serverId, String customerSchema) {
    if (!clabFactories.containsKey(serverId)) {
        DbServers d = databaseConfigurations.get(serverId);
        clabCustomerConfig.setProperty(
            "hibernate.connection.url",
            ResourceBundleService.getInstance().decorateBundle(
                "database.connection.pattern", d.getHost(),
                d.getPort()));
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(clabCustomerConfig.getProperties())
            .buildServiceRegistry();
        SessionFactory factory = clabCustomerConfig
            .buildSessionFactory(serviceRegistry);
        clabFactories.put(d.getId(), factory);
        serviceRegistry = null;
        factory = null;
    }
    Session session = clabFactories.get(serverId).withOptions()
        .tenantIdentifier(customerSchema).openSession();
    session.setDefaultReadOnly(false);
    return session;

}

很显然,我在测试时,因为我完全错过了执行了第一个错误 MultiTenantConnectionProvider
作为解释在这里

使用grepcode,我发现了AbstractMultiTenantConnectionProvider,它看起来像我想要使用的。所以我创建了扩展它的类:

public class XMLDMultiTenantConnectionProvider extends
    AbstractMultiTenantConnectionProvider {

    /**
     * 
     */
    private static final long serialVersionUID = -6679645015449636823L;

    @Override
    protected ConnectionProvider getAnyConnectionProvider() {
    return null;
    }

    @Override
    protected ConnectionProvider selectConnectionProvider(
        String tenantIdentifier) {
    // TODO Auto-generated method stub
    return null;
    }

}

但是我现在对于在这两种情况下使用什么来获得ConnectionProvider还是一无所知。你能帮助我吗?

PS:我找到了ConnectionProviderBuilder。您认为我可以以它为例吗?


阅读 351

收藏
2020-06-20

共1个答案

小编典典

我认为您可以使用以下类似的东西自己实现抽象类:

public class XMLDMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {


      private final ConnectionProvider xml1 = ConnectionProviderBuilder.buildConnectionProvider("xml1DataSource");
      private final ConnectionProvider xml2 = ConnectionProviderBuilder.buildConnectionProvider("xml2DataSource");

    /**
     * 
     */
    private static final long serialVersionUID = -6679645015449636823L;

    @Override
    protected ConnectionProvider getAnyConnectionProvider() {
         //Default Datasource (in this case i chose the first one as default)
         return xml1;
    }

    @Override
    protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {

    if( "xml1".equals(tenantIdentifier) ) 
        return xml1;

    if( "xml2".equals(tenantIdentifier) ) 
        return xml2;

    return null;
    }

}

我认为这可能是一个很好且可以理解的例子…

2020-06-20