Search in sources :

Example 16 with NaturalIdMapping

use of org.hibernate.metamodel.mapping.NaturalIdMapping in project hibernate-orm by hibernate.

the class NaturalIdTest method testMappingProperties.

@Test
public void testMappingProperties() {
    final EntityMappingType citizenEntityMapping = sessionFactory().getRuntimeMetamodels().getEntityMappingType(Citizen.class);
    final NaturalIdMapping naturalIdMapping = citizenEntityMapping.getNaturalIdMapping();
    assertThat(naturalIdMapping).withFailMessage("Class should have a natural key").isNotNull();
    assertThat(naturalIdMapping.getNaturalIdAttributes()).withFailMessage("Expecting 2 natural-id attributes, got " + naturalIdMapping.getNaturalIdAttributes().size()).hasSize(2);
}
Also used : NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) Test(org.junit.Test)

Example 17 with NaturalIdMapping

use of org.hibernate.metamodel.mapping.NaturalIdMapping in project hibernate-orm by hibernate.

the class BaseNaturalIdLoadAccessImpl method performAnyNeededCrossReferenceSynchronizations.

protected void performAnyNeededCrossReferenceSynchronizations() {
    if (!synchronizationEnabled) {
        // synchronization (this process) was disabled
        return;
    }
    final NaturalIdMapping naturalIdMapping = entityDescriptor.getNaturalIdMapping();
    if (!naturalIdMapping.isMutable()) {
        // only mutable natural-ids need this processing
        return;
    }
    final SessionImplementor session = context.getSession();
    if (!session.isTransactionInProgress()) {
        // not in a transaction so skip synchronization
        return;
    }
    final PersistenceContext persistenceContext = context.getSession().getPersistenceContextInternal();
    final Collection<?> cachedPkResolutions = persistenceContext.getNaturalIdResolutions().getCachedPkResolutions(entityPersister());
    for (Object pk : cachedPkResolutions) {
        final EntityKey entityKey = context.getSession().generateEntityKey(pk, entityPersister());
        final Object entity = persistenceContext.getEntity(entityKey);
        final EntityEntry entry = persistenceContext.getEntry(entity);
        if (entry == null) {
            if (LoaderLogging.DEBUG_ENABLED) {
                LoaderLogging.LOADER_LOGGER.debugf("Cached natural-id/pk resolution linked to null EntityEntry in persistence context : %s#%s", entityDescriptor.getEntityName(), pk);
            }
            continue;
        }
        if (!entry.requiresDirtyCheck(entity)) {
            continue;
        }
        // MANAGED is the only status we care about here...
        if (entry.getStatus() != Status.MANAGED) {
            continue;
        }
        persistenceContext.getNaturalIdResolutions().handleSynchronization(pk, entity, entityPersister());
    }
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) EntityEntry(org.hibernate.engine.spi.EntityEntry) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext)

Example 18 with NaturalIdMapping

use of org.hibernate.metamodel.mapping.NaturalIdMapping in project hibernate-orm by hibernate.

the class NaturalIdCacheKeyTest method testSerializationRoundTrip.

@Test
public void testSerializationRoundTrip() throws Exception {
    final SessionFactoryImplementor sessionFactoryImplementor = mock(SessionFactoryImplementor.class);
    final SessionImplementor sessionImplementor = mock(SessionImplementor.class);
    final RuntimeMetamodelsImplementor runtimeMetamodels = mock(RuntimeMetamodelsImplementor.class);
    final EntityPersister entityPersister = mock(EntityPersister.class);
    final NaturalIdMapping naturalIdMapping = mock(NaturalIdMapping.class);
    when(sessionImplementor.getFactory()).thenReturn(sessionFactoryImplementor);
    when(sessionFactoryImplementor.getRuntimeMetamodels()).thenReturn(runtimeMetamodels);
    when(runtimeMetamodels.getEntityMappingType(anyString())).thenReturn(entityPersister);
    when(entityPersister.getRootEntityName()).thenReturn("EntityName");
    when(entityPersister.getNaturalIdMapping()).thenReturn(naturalIdMapping);
    when(naturalIdMapping.disassemble(any(), eq(sessionImplementor))).thenAnswer(invocation -> invocation.getArguments()[0]);
    when(naturalIdMapping.calculateHashCode(any(), eq(sessionImplementor))).thenAnswer(invocation -> invocation.getArguments()[0].hashCode());
    final NaturalIdCacheKey key = (NaturalIdCacheKey) DefaultCacheKeysFactory.staticCreateNaturalIdKey(new Object[] { "a", "b", "c" }, entityPersister, sessionImplementor);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(key);
    final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final NaturalIdCacheKey keyClone = (NaturalIdCacheKey) ois.readObject();
    assertEquals(key, keyClone);
    assertEquals(key.hashCode(), keyClone.hashCode());
    assertEquals(key.toString(), keyClone.toString());
    assertEquals(key.getEntityName(), keyClone.getEntityName());
    assertArrayEquals((Object[]) key.getNaturalIdValues(), (Object[]) keyClone.getNaturalIdValues());
    assertEquals(key.getTenantId(), keyClone.getTenantId());
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) NaturalIdCacheKey(org.hibernate.cache.internal.NaturalIdCacheKey) ByteArrayInputStream(java.io.ByteArrayInputStream) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) RuntimeMetamodelsImplementor(org.hibernate.metamodel.spi.RuntimeMetamodelsImplementor) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 19 with NaturalIdMapping

use of org.hibernate.metamodel.mapping.NaturalIdMapping in project hibernate-orm by hibernate.

the class CompoundNaturalIdMappingTest method test.

@Test
public void test() {
    final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
    try {
        Metadata meta = new MetadataSources(ssr).addAnnotatedClass(PostalCarrier.class).addAnnotatedClass(Country.class).buildMetadata();
        ((MetadataImplementor) meta).validate();
        final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) meta.buildSessionFactory();
        try {
            final EntityMappingType entityMappingType = sessionFactory.getRuntimeMetamodels().getEntityMappingType(PostalCarrier.class);
            final NaturalIdMapping naturalIdMapping = entityMappingType.getNaturalIdMapping();
            final List<SingularAttributeMapping> naturalIdAttributes = naturalIdMapping.getNaturalIdAttributes();
            assertThat(naturalIdAttributes.size(), is(2));
            assertThat(naturalIdAttributes.get(0).getAttributeName(), is("code"));
            assertThat(naturalIdAttributes.get(1).getAttributeName(), is("country"));
        } finally {
            sessionFactory.close();
        }
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) SingularAttributeMapping(org.hibernate.metamodel.mapping.SingularAttributeMapping) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) Test(org.junit.jupiter.api.Test)

Example 20 with NaturalIdMapping

use of org.hibernate.metamodel.mapping.NaturalIdMapping in project hibernate-orm by hibernate.

the class ImmutableManyToOneNaturalIdHbmTest method checkingMapping.

@Test
@TestForIssue(jiraKey = "HHH-10360")
public void checkingMapping(SessionFactoryScope scope) {
    final RuntimeMetamodels runtimeMetamodels = scope.getSessionFactory().getRuntimeMetamodels();
    final EntityMappingType childMapping = runtimeMetamodels.getEntityMappingType(Child.class.getName());
    final EntityPersister persister = childMapping.getEntityPersister();
    final EntityMetamodel entityMetamodel = persister.getEntityMetamodel();
    final int nameIndex = entityMetamodel.getPropertyIndex("name");
    final int parentIndex = entityMetamodel.getPropertyIndex("parent");
    // checking alphabetic sort in relation to EntityPersister/EntityMetamodel
    assertThat(nameIndex, lessThan(parentIndex));
    assertFalse(persister.getPropertyUpdateability()[nameIndex]);
    assertFalse(persister.getPropertyUpdateability()[parentIndex]);
    // nullability is not specified for either properties making up
    // the natural ID, so they should be non-nullable by hbm-specific default
    assertFalse(persister.getPropertyNullability()[nameIndex]);
    assertFalse(persister.getPropertyNullability()[parentIndex]);
    final NaturalIdMapping naturalIdMapping = childMapping.getNaturalIdMapping();
    assertNotNull(naturalIdMapping);
    assertThat(naturalIdMapping.getNaturalIdAttributes().size(), is(2));
    final SingularAttributeMapping first = naturalIdMapping.getNaturalIdAttributes().get(0);
    assertThat(first.getAttributeName(), is("name"));
    final StateArrayContributorMetadata firstMetadata = first.getAttributeMetadataAccess().resolveAttributeMetadata(null);
    assertFalse(firstMetadata.getMutabilityPlan().isMutable());
    final SingularAttributeMapping second = naturalIdMapping.getNaturalIdAttributes().get(1);
    assertThat(second.getAttributeName(), is("parent"));
    final StateArrayContributorMetadata secondMetadata = second.getAttributeMetadataAccess().resolveAttributeMetadata(null);
    assertFalse(secondMetadata.getMutabilityPlan().isMutable());
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) RuntimeMetamodels(org.hibernate.metamodel.RuntimeMetamodels) SingularAttributeMapping(org.hibernate.metamodel.mapping.SingularAttributeMapping) StateArrayContributorMetadata(org.hibernate.metamodel.mapping.StateArrayContributorMetadata) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) EntityMetamodel(org.hibernate.tuple.entity.EntityMetamodel) Test(org.junit.jupiter.api.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Aggregations

NaturalIdMapping (org.hibernate.metamodel.mapping.NaturalIdMapping)22 EntityPersister (org.hibernate.persister.entity.EntityPersister)13 Test (org.junit.jupiter.api.Test)8 EntityMappingType (org.hibernate.metamodel.mapping.EntityMappingType)5 SingularAttributeMapping (org.hibernate.metamodel.mapping.SingularAttributeMapping)5 MappingMetamodel (org.hibernate.metamodel.MappingMetamodel)4 EntityMetamodel (org.hibernate.tuple.entity.EntityMetamodel)3 NaturalIdDataAccess (org.hibernate.cache.spi.access.NaturalIdDataAccess)2 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)2 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)2 PersistentClass (org.hibernate.mapping.PersistentClass)2 Property (org.hibernate.mapping.Property)2 RuntimeMetamodels (org.hibernate.metamodel.RuntimeMetamodels)2 StateArrayContributorMetadata (org.hibernate.metamodel.mapping.StateArrayContributorMetadata)2 TestForIssue (org.hibernate.testing.TestForIssue)2 Test (org.junit.Test)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 ObjectInputStream (java.io.ObjectInputStream)1 ObjectOutputStream (java.io.ObjectOutputStream)1