Search in sources :

Example 21 with EntityDataAccess

use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.

the class BasicUnstructuredCachingOfConvertedValueTest method basicCacheStructureTest.

@Test
@TestForIssue(jiraKey = "HHH-9615")
@SuppressWarnings("unchecked")
public void basicCacheStructureTest() {
    EntityPersister persister = sessionFactory().getMetamodel().entityPersisters().get(Address.class.getName());
    final DomainDataRegion region = persister.getCacheAccessStrategy().getRegion();
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // test during store...
    PostalAreaConverter.clearCounts();
    Session session = openSession();
    session.getTransaction().begin();
    session.save(new Address(1, "123 Main St.", null, PostalArea._78729));
    session.getTransaction().commit();
    session.close();
    {
        inSession(s -> {
            final EntityDataAccess entityDataAccess = region.getEntityDataAccess(persister.getNavigableRole());
            final Object cacheKey = entityDataAccess.generateCacheKey(1, persister, sessionFactory(), null);
            final Object cachedItem = entityDataAccess.get(s, cacheKey);
            final StandardCacheEntryImpl state = (StandardCacheEntryImpl) cachedItem;
            // this is the point of the Jira.. that this "should be" the converted value
            assertThat(state.getDisassembledState()[postalAreaAttributeIndex], instanceOf(PostalArea.class));
        });
    }
    assertThat(PostalAreaConverter.toDatabaseCallCount, is(1));
    assertThat(PostalAreaConverter.toDomainCallCount, is(0));
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // test during load...
    PostalAreaConverter.clearCounts();
    sessionFactory().getCache().evictAll();
    session = openSession();
    session.getTransaction().begin();
    Address address = session.get(Address.class, 1);
    session.getTransaction().commit();
    session.close();
    {
        inSession(s -> {
            final EntityDataAccess entityDataAccess = region.getEntityDataAccess(persister.getNavigableRole());
            final Object cacheKey = entityDataAccess.generateCacheKey(1, persister, sessionFactory(), null);
            final Object cachedItem = entityDataAccess.get(s, cacheKey);
            final StandardCacheEntryImpl state = (StandardCacheEntryImpl) cachedItem;
            // this is the point of the Jira.. that this "should be" the converted value
            assertThat(state.getDisassembledState()[postalAreaAttributeIndex], instanceOf(PostalArea.class));
        });
    }
    assertThat(PostalAreaConverter.toDatabaseCallCount, is(0));
    assertThat(PostalAreaConverter.toDomainCallCount, is(1));
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // cleanup
    session = openSession();
    session.getTransaction().begin();
    session.delete(address);
    session.getTransaction().commit();
    session.close();
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) CoreMatchers.is(org.hamcrest.CoreMatchers.is) EntityPersister(org.hibernate.persister.entity.EntityPersister) BaseNonConfigCoreFunctionalTestCase(org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase) AvailableSettings(org.hibernate.cfg.AvailableSettings) CachingRegionFactory(org.hibernate.testing.cache.CachingRegionFactory) Session(org.hibernate.Session) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) Test(org.junit.Test) StandardCacheEntryImpl(org.hibernate.cache.spi.entry.StandardCacheEntryImpl) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) TestForIssue(org.hibernate.testing.TestForIssue) Map(java.util.Map) DomainDataRegion(org.hibernate.cache.spi.DomainDataRegion) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) StandardCacheEntryImpl(org.hibernate.cache.spi.entry.StandardCacheEntryImpl) DomainDataRegion(org.hibernate.cache.spi.DomainDataRegion) Session(org.hibernate.Session) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 22 with EntityDataAccess

use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.

the class DomainDataRegionTest method testBasicUsage.

@Test
public void testBasicUsage() {
    final Region region = sessionFactory().getCache().getRegion(TestHelper.entityRegionNames[0]);
    final DomainDataRegionTemplate domainDataRegion = assertTyping(DomainDataRegionTemplate.class, region);
    // see if we can get access to all of the access objects we think should be defined in this region
    final EntityDataAccess itemAccess = domainDataRegion.getEntityDataAccess(sessionFactory().getMetamodel().entityPersister(Item.class).getNavigableRole());
    assertThat(itemAccess.getAccessType(), equalTo(AccessType.READ_WRITE));
    assertThat(sessionFactory().getMetamodel().entityPersister(VersionedItem.class).getCacheAccessStrategy().getAccessType(), equalTo(AccessType.READ_WRITE));
    assertThat(sessionFactory().getMetamodel().entityPersister(Event.class).getCacheAccessStrategy().getAccessType(), equalTo(AccessType.READ_WRITE));
    assertThat(sessionFactory().getMetamodel().collectionPersister(Event.class.getName() + ".participants").getCacheAccessStrategy().getAccessType(), equalTo(AccessType.READ_WRITE));
}
Also used : DomainDataRegionTemplate(org.hibernate.cache.spi.support.DomainDataRegionTemplate) VersionedItem(org.hibernate.jcache.test.domain.VersionedItem) Region(org.hibernate.cache.spi.Region) Event(org.hibernate.jcache.test.domain.Event) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) Test(org.junit.Test)

Example 23 with EntityDataAccess

use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.

the class EnabledCaching method containsEntity.

@Override
public boolean containsEntity(String entityName, Serializable identifier) {
    final EntityPersister entityDescriptor = sessionFactory.getMetamodel().entityPersister(entityName);
    final EntityDataAccess cacheAccess = entityDescriptor.getCacheAccessStrategy();
    if (cacheAccess == null) {
        return false;
    }
    final Object key = cacheAccess.generateCacheKey(identifier, entityDescriptor, sessionFactory, null);
    return cacheAccess.contains(key);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Example 24 with EntityDataAccess

use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.

the class MetamodelImpl method initialize.

/**
 * Prepare the metamodel using the information from the collection of Hibernate
 * {@link PersistentClass} models
 *
 * @param mappingMetadata The mapping information
 * @param jpaMetaModelPopulationSetting Should the JPA Metamodel be built as well?
 */
public void initialize(MetadataImplementor mappingMetadata, JpaMetaModelPopulationSetting jpaMetaModelPopulationSetting) {
    this.imports.putAll(mappingMetadata.getImports());
    primeSecondLevelCacheRegions(mappingMetadata);
    final PersisterCreationContext persisterCreationContext = new PersisterCreationContext() {

        @Override
        public SessionFactoryImplementor getSessionFactory() {
            return sessionFactory;
        }

        @Override
        public MetadataImplementor getMetadata() {
            return mappingMetadata;
        }
    };
    final PersisterFactory persisterFactory = sessionFactory.getServiceRegistry().getService(PersisterFactory.class);
    for (final PersistentClass model : mappingMetadata.getEntityBindings()) {
        final NavigableRole rootEntityRole = new NavigableRole(model.getRootClass().getEntityName());
        final EntityDataAccess accessStrategy = sessionFactory.getCache().getEntityRegionAccess(rootEntityRole);
        final NaturalIdDataAccess naturalIdAccessStrategy = sessionFactory.getCache().getNaturalIdCacheRegionAccessStrategy(rootEntityRole);
        final EntityPersister cp = persisterFactory.createEntityPersister(model, accessStrategy, naturalIdAccessStrategy, persisterCreationContext);
        entityPersisterMap.put(model.getEntityName(), cp);
        if (cp.getConcreteProxyClass() != null && cp.getConcreteProxyClass().isInterface() && !Map.class.isAssignableFrom(cp.getConcreteProxyClass()) && cp.getMappedClass() != cp.getConcreteProxyClass()) {
            if (cp.getMappedClass().equals(cp.getConcreteProxyClass())) {
                // this part handles an odd case in the Hibernate test suite where we map an interface
                // as the class and the proxy.  I cannot think of a real life use case for that
                // specific test, but..
                log.debugf("Entity [%s] mapped same interface [%s] as class and proxy", cp.getEntityName(), cp.getMappedClass());
            } else {
                final String old = entityProxyInterfaceMap.put(cp.getConcreteProxyClass(), cp.getEntityName());
                if (old != null) {
                    throw new HibernateException(String.format(Locale.ENGLISH, "Multiple entities [%s, %s] named the same interface [%s] as their proxy which is not supported", old, cp.getEntityName(), cp.getConcreteProxyClass().getName()));
                }
            }
        }
    }
    for (final Collection model : mappingMetadata.getCollectionBindings()) {
        final NavigableRole navigableRole = new NavigableRole(model.getRole());
        final CollectionDataAccess accessStrategy = sessionFactory.getCache().getCollectionRegionAccess(navigableRole);
        final CollectionPersister persister = persisterFactory.createCollectionPersister(model, accessStrategy, persisterCreationContext);
        collectionPersisterMap.put(model.getRole(), persister);
        Type indexType = persister.getIndexType();
        if (indexType != null && indexType.isAssociationType() && !indexType.isAnyType()) {
            String entityName = ((AssociationType) indexType).getAssociatedEntityName(sessionFactory);
            Set<String> roles = collectionRolesByEntityParticipant.get(entityName);
            if (roles == null) {
                roles = new HashSet<>();
                collectionRolesByEntityParticipant.put(entityName, roles);
            }
            roles.add(persister.getRole());
        }
        Type elementType = persister.getElementType();
        if (elementType.isAssociationType() && !elementType.isAnyType()) {
            String entityName = ((AssociationType) elementType).getAssociatedEntityName(sessionFactory);
            Set<String> roles = collectionRolesByEntityParticipant.get(entityName);
            if (roles == null) {
                roles = new HashSet<>();
                collectionRolesByEntityParticipant.put(entityName, roles);
            }
            roles.add(persister.getRole());
        }
    }
    // after *all* persisters and named queries are registered
    entityPersisterMap.values().forEach(EntityPersister::generateEntityDefinition);
    for (EntityPersister persister : entityPersisterMap.values()) {
        persister.postInstantiate();
        registerEntityNameResolvers(persister, entityNameResolvers);
    }
    collectionPersisterMap.values().forEach(CollectionPersister::postInstantiate);
    if (jpaMetaModelPopulationSetting != JpaMetaModelPopulationSetting.DISABLED) {
        MetadataContext context = new MetadataContext(sessionFactory, mappingMetadata.getMappedSuperclassMappingsCopy(), jpaMetaModelPopulationSetting);
        for (PersistentClass entityBinding : mappingMetadata.getEntityBindings()) {
            locateOrBuildEntityType(entityBinding, context);
        }
        handleUnusedMappedSuperclasses(context);
        context.wrapUp();
        this.jpaEntityTypeMap.putAll(context.getEntityTypeMap());
        this.jpaEmbeddableTypeMap.putAll(context.getEmbeddableTypeMap());
        this.jpaMappedSuperclassTypeMap.putAll(context.getMappedSuperclassTypeMap());
        this.jpaEntityTypesByEntityName.putAll(context.getEntityTypesByEntityName());
        applyNamedEntityGraphs(mappingMetadata.getNamedEntityGraphs().values());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) HibernateException(org.hibernate.HibernateException) PersisterFactory(org.hibernate.persister.spi.PersisterFactory) NaturalIdDataAccess(org.hibernate.cache.spi.access.NaturalIdDataAccess) CollectionDataAccess(org.hibernate.cache.spi.access.CollectionDataAccess) PersisterCreationContext(org.hibernate.persister.spi.PersisterCreationContext) AccessType(org.hibernate.cache.spi.access.AccessType) ManagedType(javax.persistence.metamodel.ManagedType) MappedSuperclassType(javax.persistence.metamodel.MappedSuperclassType) EntityType(javax.persistence.metamodel.EntityType) AssociationType(org.hibernate.type.AssociationType) EmbeddableType(javax.persistence.metamodel.EmbeddableType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) AssociationType(org.hibernate.type.AssociationType) NavigableRole(org.hibernate.metamodel.model.domain.NavigableRole) Collection(org.hibernate.mapping.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) PersistentClass(org.hibernate.mapping.PersistentClass) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Aggregations

EntityDataAccess (org.hibernate.cache.spi.access.EntityDataAccess)24 EntityPersister (org.hibernate.persister.entity.EntityPersister)15 Serializable (java.io.Serializable)8 CacheEntry (org.hibernate.cache.spi.entry.CacheEntry)5 EntityEntry (org.hibernate.engine.spi.EntityEntry)5 AssertionFailure (org.hibernate.AssertionFailure)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)4 Map (java.util.Map)3 HibernateException (org.hibernate.HibernateException)3 DomainDataRegion (org.hibernate.cache.spi.DomainDataRegion)3 SoftLock (org.hibernate.cache.spi.access.SoftLock)3 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)3 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)3 Test (org.junit.Test)3 CoreMatchers.instanceOf (org.hamcrest.CoreMatchers.instanceOf)2 CoreMatchers.is (org.hamcrest.CoreMatchers.is)2 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)2 LockMode (org.hibernate.LockMode)2 Session (org.hibernate.Session)2 CollectionDataAccess (org.hibernate.cache.spi.access.CollectionDataAccess)2