4

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)?

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
John Ament
  • 11,595
  • 1
  • 36
  • 45

2 Answers2

3

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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • Hmm so that would imply that all tenant data ends up within the same cache. Basically like a column discriminator. – John Ament Jan 19 '17 at 11:29
  • There's a single region for the Query Cache, yes. So all entries go in the same region. – Vlad Mihalcea Jan 19 '17 at 11:30
  • Hibernate's Query Cache is independent of the second-level caching mechanism so the QueryKey class may not be ideal as proof that the second-level cache is multi-tenant aware but the documentation does state that it's second level cache supports multitenancy. – Night Owl Jul 05 '17 at 15:53
3

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.

Night Owl
  • 4,198
  • 4
  • 28
  • 37