简体   繁体   中英

Using Hibernate 2nd Level Cache and Multitenancy

I'm presently using Hibernate with MultiTenancy options (schema per tenant in MySQL... so DB per tenant). We have an implementation of the connection provider and tenant identifier which properly switches DB schemas for us. Great.

Now, we want to begin exploring using 2nd Level Cache in our application. Going through the docs, it not clear if this works properly or not.

For a given tenant database, there will be rows with given DB ids... 1,2,3 etc as primary key. When I have two tenant DBs in play, are those entities stored separately? Will Hibernate correctly create caches per tenant (effectively)?

Yes, it should because take a look on the QueryKey :

public class QueryKey 
    implements Serializable {
    private final String sqlQueryString;
    private final Type[] positionalParameterTypes;
    private final Object[] positionalParameterValues;
    private final Map namedParameters;
    private final Integer firstRow;
    private final Integer maxRows;
    private final String tenantIdentifier;
    private final Set filterKeys;

    private final CacheableResultTransformer customTransformer;

    private transient int hashCode;

    ...

}

As you can see, there's a tenantIdnetifier field so each query cache entry is relative to a Tenant.

If this does not work for you, then it's a bug.

In section 19.4.3 "Caching", which was section 16.3.3 in some earlier versions, the Hibernate 5.2 documentation says:

Multitenancy support in Hibernate works seamlessly with the Hibernate second level cache. The key used to cache data encodes the tenant identifier .

The above quote seems definitive but in the same section an informational note adds:

Currently, schema export will not really work with multitenancy. That may not change. The JPA expert group is in the process of defining multitenancy support for an upcoming version of the specification.

The note directly addresses schema export but it's implications for the second level cache and multitenancy aren't clear. It seems to suggest that native Hibernate fully supports multitenacy but it's JPA implementation may not although I could be over reading that section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM