具有 Spring + Hibernate 的多租户:“SessionFactory 配置为多租户,但未指定租户标识符”配置.xmlMultiTenantConnectionProvider.javaCurrentTenantidentifierResolver.java

2022-09-02 09:37:45

在Spring 3应用程序中,我试图通过Hibernate 4的本机MultiTenantConnectionProviderCurrentTenantIdentifierResolver实现多租户。我看到在Hibernate 4.1.3中存在此问题,但我运行的是4.1.9,并且仍然得到类似的异常:

   Caused by:

org.hibernate.HibernateException: SessionFactory configured for multi-tenancy, but no tenant identifier specified
    at org.hibernate.internal.AbstractSessionImpl.<init>(AbstractSessionImpl.java:84)
    at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:239)
    at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1597)
    at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:963)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:328)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:334)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    at com.afflatus.edu.thoth.repository.UserRepository$$EnhancerByCGLIB$$c844ce96.getAllUsers(<generated>)
    at com.afflatus.edu.thoth.service.UserService.getAllUsers(UserService.java:29)
    at com.afflatus.edu.thoth.HomeController.hello(HomeController.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:671)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:448)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:138)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:564)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:213)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1070)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:375)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:175)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1004)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:258)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:109)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:439)
    at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:246)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:265)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:240)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:589)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:520)
    at java.lang.Thread.run(Thread.java:722) enter code here

以下是相关代码。在 我现在只是写了一些愚蠢的代码,每次只返回一个新连接,并且 此时总是返回相同的ID。显然,这个逻辑是在我设法获得要实例化的连接之后实现的。MultiTenantConnectionProviderCurrentTenantIdentifierResolver

配置.xml

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>com.afflatus.edu.thoth.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl">${hibernate.dbm2ddl}</prop>
            <prop key="hibernate.multiTenancy">DATABASE</prop>
            <prop key="hibernate.multi_tenant_connection_provider">com.afflatus.edu.thoth.connection.MultiTenantConnectionProviderImpl</prop>
            <prop key="hibernate.tenant_identifier_resolver">com.afflatus.edu.thoth.context.MultiTenantIdentifierResolverImpl</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="autodetectDataSource" value="false" />
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

MultiTenantConnectionProvider.java

package com.afflatus.edu.thoth.connection;

import java.util.Properties;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.service.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.hibernate.cfg.*;

public class MultiTenantConnectionProviderImpl extends AbstractMultiTenantConnectionProvider {

    private final Map<String, ConnectionProvider> connectionProviders
        = new HashMap<String, ConnectionProvider>();

    @Override
    protected ConnectionProvider getAnyConnectionProvider() {

        System.out.println("barfoo");
        Properties properties = getConnectionProperties();

        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/test");
        ds.setUsername("root");
        ds.setPassword("");

        InjectedDataSourceConnectionProvider defaultProvider = new InjectedDataSourceConnectionProvider();
        defaultProvider.setDataSource(ds);
        defaultProvider.configure(properties);

        return (ConnectionProvider) defaultProvider;
    }


    @Override
    protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
        System.out.println("foobar");
        Properties properties = getConnectionProperties();

        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/test2");
        ds.setUsername("root");
        ds.setPassword("");

        InjectedDataSourceConnectionProvider defaultProvider = new InjectedDataSourceConnectionProvider();
        defaultProvider.setDataSource(ds);
        defaultProvider.configure(properties);

        return (ConnectionProvider) defaultProvider;
    }

    private Properties getConnectionProperties() {
        Properties properties = new Properties();
        properties.put(AvailableSettings.DIALECT, "org.hibernate.dialect.MySQLDialect");
        properties.put(AvailableSettings.DRIVER, "com.mysql.jdbc.Driver");
        properties.put(AvailableSettings.URL, "jdbc:mysql://127.0.0.1:3306/test");
        properties.put(AvailableSettings.USER, "root");
        properties.put(AvailableSettings.PASS, "");

        return properties;

    }
}

CurrentTenantidentifierResolver.java

package com.afflatus.edu.thoth.context;

import org.hibernate.context.spi.CurrentTenantIdentifierResolver;

public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver {

    public String resolveCurrentTenantIdentifier() {
        return "1";
    }

    public boolean validateExistingCurrentSessions() {
        return true;
    }

}

有人能看到任何特别错误的东西吗?这将在打开事务后立即引发异常。似乎 没有正确打开会话,或者只是忽略了 返回的值,我认为这是 Hibernate 4.1.3 中的问题;这应该已经解决了。SessionFactorySessionCurrentTenantIdentifierResolver


答案 1

您是否在代码中使用任何地方(即标记服务或dao类/方法)?
在我注释掉服务类之前,我遇到了同样的错误。
我认为它与 Hibernate 4 的默认 openSessionInThread 行为有关。@Transactional@Transactional

我还配置了休眠状态,但没有自定义实现和。我使用基于 jndi 的方法,将 hibernate.connection.datasource 设置为 java://comp/env/jdbc/,然后将 jndi 资源的名称传入我的 dao 方法,这些方法调用ConnectionProviderTenantIdentifierResolver

sessionFactory.withOptions().tenantIdentifier(tenant).openSession();

我仍然在玩,看看我是否可以使用 配置,但是基于jndi的方法在线程行为中默认会话现在似乎正在工作。@Transactional


答案 2

Foreward:虽然我接受了这个包含代码的答案,但如果你认为这很有用,请投票给Darren的答案。他就是我能够解决这个问题的原因。

好了,我们开始吧...

正如Darren所指出的,这实际上是SessionFactory不正确地实例化会话的问题。如果要手动实例化会话,则没有问题。例如:

sessionFactory.withOptions().tenantIdentifier(tenant).openSession();

但是,该批注会导致 SessionFactory 打开一个会话,该会话不会从 中提取租户标识符。@TransactionalsessionFactory.getCurrentSession()CurrentTenantIdentifierResolver

Darren 建议在 DAO 层中手动打开会话,但这意味着每个 DAO 方法都有一个本地范围的事务。执行此操作的更好位置是在服务层上。每个服务层调用(即)可以调用多个DAO方法。这些中的每一个都应该绑定到同一个事务是有道理的,因为它们在逻辑上是相关的。doSomeLogicalTask()

此外,我不喜欢在每个服务层方法中复制代码来创建和管理事务的想法。相反,我使用AOP将每个方法包装在我的服务层中,并提供实例化新方法和处理事务的建议。该方面将电流存储在堆栈中,DAO层可以访问该堆栈以进行查询。SessionSessionTheadLocal

所有这些工作将允许接口和实现与它们修复错误对应的接口和实现保持相同,除了DAO超类中的一行将从堆栈而不是.一旦错误得到修复,就可以更改。SessionThreadLocalSessionFactory

一旦我稍微清理一下,我很快就会发布代码。如果有人发现任何问题,请随时在下面讨论。


推荐