3

我正在尝试使用休眠多租户(来自第 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。你觉得我可以以此为榜样效仿吗?

4

1 回答 1

3

我认为您可以拥有自己的抽象类实现,如下所示:

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;
    }

}

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

于 2012-09-10T13:10:17.337 回答