1 year ago

#382437

test-img

sergiopf

AbstractMultiTenantConnectionProvider change context automatically before get connection

I'm working with Spring multitenancy framework, and i'm trying to set the TenanContext depending on a property in each Entity class. The interceptor that I use doesn't set the TenantSelector before each transaction, and I don't find any to achieve it (onLoad do everything during the application load but not before each transaction). I'm trying other interceptors from org.hibernate.EmptyInterceptor but any do what I need.

This is the interceptor that I use:

LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setEntityInterceptor(new MultitenancyInterceptor());

And its implementation:

public class MultitenancyInterceptor extends EmptyInterceptor {

    @Override
    public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        //logic to update the TenantContext
        return super.onLoad(entity, id, state, propertyNames, types);
    }
}

Is there any interceptor which can help me to calculate the TenantContext before each getConnection from AbstractMultiTenantConnectionProvider?

public abstract class MultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
...
    @Override
    public Connection getConnection(String tenantIdentifier)
            throws SQLException {
        Connection connection = super.getConnection(tenantIdentifier);
        connection.createStatement()
                .execute(String.format("USE `%s`;", tenantIdentifier));
        return connection;
    }
}

spring-boot

connection

multi-tenant

interceptor

0 Answers

Your Answer

Accepted video resources