Hibernate built-in request and cache mechanism

I have a question regarding the Hibernate caching mechanism. I read in the articles that running SQLquery in hibernate itself invalidates all areas of the cache because hibernate has no idea which particular object it will affect. Here, all the cache areas are different areas of the second level cache or both cache levels (first level cache, second level cache) or only second level cache or only first level cache?

+4
source share
1 answer

This article explains how Hibernate cache works and the impact of native queries on existing cache entries.

Using SQLQuery, Hibernate could not know in which areas of the cache you can affect, but, fortunately, you can explicitly instruct it:

SQLQuery sqlQuery = session.createSQLQuery(
    "UPDATE CUSTOMER SET ... WHERE ..."); 
sqlQuery.addSynchronizedEntityClass(Person.class); int
int updateCount = sqlQuery.executeUpdate();

Thus, he knows which request caches are invalid, otherwise he can cancel everything:

private static class EntityCleanup {
    private final EntityRegionAccessStrategy cacheAccess;
    private final SoftLock cacheLock;

    private EntityCleanup(EntityRegionAccessStrategy cacheAccess) {
        this.cacheAccess = cacheAccess;
        this.cacheLock = cacheAccess.lockRegion();
        cacheAccess.removeAll();
    }

    private void release() {
        cacheAccess.unlockRegion( cacheLock );
    }
}

private static class CollectionCleanup {
    private final CollectionRegionAccessStrategy cacheAccess;
    private final SoftLock cacheLock;

    private CollectionCleanup(CollectionRegionAccessStrategy cacheAccess) {
        this.cacheAccess = cacheAccess;
        this.cacheLock = cacheAccess.lockRegion();
        cacheAccess.removeAll();
    }

    private void release() {
        cacheAccess.unlockRegion( cacheLock );
    }
}

private class NaturalIdCleanup {
    private final NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy;
    private final SoftLock cacheLock;

    public NaturalIdCleanup(NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy) {
        this.naturalIdCacheAccessStrategy = naturalIdCacheAccessStrategy;
        this.cacheLock = naturalIdCacheAccessStrategy.lockRegion();
        naturalIdCacheAccessStrategy.removeAll();
    }

    private void release() {
        naturalIdCacheAccessStrategy.unlockRegion( cacheLock );
    }
}

So, as you can see, all data from the region has been evicted.

. ( a.k.a.) , , " ", . (HQL native) , db , 1- .

, . , , (), .

, , - Hibernate, , .

+10

Source: https://habr.com/ru/post/1542775/


All Articles