2009-03-31 8 views
5

Sto utilizzando Hibernate come soluzione ORM, con EHCache come cache di secondo livello (lettura-scrittura).Manipolazione di Hibernate 2nd Level Cache

La mia domanda è: è possibile accedere direttamente alla cache di secondo livello?

Voglio accedere a questo: http://www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/ReadWriteCache.html

Come posso accedere alla stessa ReadWriteCache che viene utilizzato da Hibernate?

Ho alcuni inserimenti JDBC diretti/personalizzati che sto facendo e voglio aggiungere tali oggetti alla cache di 2 ° livello.

risposta

6

che chiamerei "AfterInsert" sul EntityPersister mappato a vostra entità dato lettura/scrittura è una strategia di concorrenza asincrono. Ho messo insieme questo dopo aver guardato attraverso la fonte Hibernate 3.3. Non sono al 100% che questo funzionerà, ma mi sembra buono.

EntityPersister persister = ((SessionFactoryImpl) session.getSessionFactory()).getEntityPersister("theNameOfYourEntity"); 

if (persister.hasCache() && 
    !persister.isCacheInvalidationRequired() && 
    session.getCacheMode().isPutEnabled()) { 

    CacheKey ck = new CacheKey( 
        theEntityToBeCached.getId(), 
        persister.getIdentifierType(), 
        persister.getRootEntityName(), 
        session.getEntityMode(), 
        session.getFactory() 
       ); 

    persister.getCacheAccessStrategy().afterInsert(ck, theEntityToBeCached, null); 
} 

-

/** 
* Called after an item has been inserted (after the transaction completes), 
* instead of calling release(). 
* This method is used by "asynchronous" concurrency strategies. 
* 
* @param key The item key 
* @param value The item 
* @param version The item's version value 
* @return Were the contents of the cache actual changed by this operation? 
* @throws CacheException Propogated from underlying {@link org.hibernate.cache.Region} 
*/ 
public boolean afterInsert(Object key, Object value, Object version) throws CacheException; 
1

Ho fatto questo per creare il mio fornitore di cache. Ho appena annullato EhCacheProvider e ho usato la mia variabile per il gestore in modo da poterla restituire in modo statico. Una volta ottenuto CacheManager, è possibile chiamare manager.getCache (class_name) per ottenere una cache per quel tipo di entità. Poi si crea un CacheKey utilizzando la chiave primaria, il tipo e il nome della classe:

CacheKey cacheKey = new CacheKey(key, type, class_name, EntityMode.POJO, 
    (SessionFactoryImplementor)session.getSessionFactory()); 

la cache è essenzialmente una mappa in modo da poter verificare se l'oggetto si trova nella cache, o scorrere le entità .

Potrebbe esserci un modo per accedere a CacheProvider quando si crea inizialmente SessionFactory che evita di dover implementare il proprio.

0

Sia Hibernate e JPA ora forniscono accesso diretto alla cache di 2 ° livello sottostante:

sessionFactory.getCache(); 
entityManager.getCache(); 
Problemi correlati