Search in sources :

Example 31 with Collection

use of org.hibernate.mapping.Collection in project hibernate-orm by hibernate.

the class DefaultNamingCollectionElementTest method isCollectionColumnPresent.

private void isCollectionColumnPresent(String collectionOwner, String propertyName, String columnName) {
    final Collection collection = metadata().getCollectionBinding(collectionOwner + "." + propertyName);
    final Iterator columnIterator = collection.getCollectionTable().getColumnIterator();
    boolean hasDefault = false;
    while (columnIterator.hasNext()) {
        Column column = (Column) columnIterator.next();
        if (columnName.equals(column.getName()))
            hasDefault = true;
    }
    assertTrue("Could not find " + columnName, hasDefault);
}
Also used : Column(org.hibernate.mapping.Column) Iterator(java.util.Iterator) Collection(org.hibernate.mapping.Collection)

Example 32 with Collection

use of org.hibernate.mapping.Collection in project hibernate-orm by hibernate.

the class ElementCollectionTests method testSimpleConvertUsage.

@Test
public void testSimpleConvertUsage() throws MalformedURLException {
    // first some assertions of the metamodel
    PersistentClass entityBinding = metadata().getEntityBinding(TheEntity.class.getName());
    assertNotNull(entityBinding);
    Property setAttributeBinding = entityBinding.getProperty("set");
    Collection setBinding = (Collection) setAttributeBinding.getValue();
    assertTyping(AttributeConverterTypeAdapter.class, setBinding.getElement().getType());
    Property mapAttributeBinding = entityBinding.getProperty("map");
    IndexedCollection mapBinding = (IndexedCollection) mapAttributeBinding.getValue();
    assertTyping(AttributeConverterTypeAdapter.class, mapBinding.getIndex().getType());
    assertTyping(AttributeConverterTypeAdapter.class, mapBinding.getElement().getType());
    // now lets try to use the model, integration-testing-style!
    TheEntity entity = new TheEntity(1);
    Session s = openSession();
    s.beginTransaction();
    s.save(entity);
    s.getTransaction().commit();
    s.close();
    s = openSession();
    s.beginTransaction();
    TheEntity retrieved = (TheEntity) s.load(TheEntity.class, 1);
    assertEquals(1, retrieved.getSet().size());
    assertEquals(new ValueType("set_value"), retrieved.getSet().iterator().next());
    assertEquals(1, retrieved.getMap().size());
    assertEquals(new ValueType("map_value"), retrieved.getMap().get(new ValueType("map_key")));
    s.delete(retrieved);
    s.getTransaction().commit();
    s.close();
}
Also used : IndexedCollection(org.hibernate.mapping.IndexedCollection) Collection(org.hibernate.mapping.Collection) ElementCollection(javax.persistence.ElementCollection) Property(org.hibernate.mapping.Property) IndexedCollection(org.hibernate.mapping.IndexedCollection) PersistentClass(org.hibernate.mapping.PersistentClass) Session(org.hibernate.Session) Test(org.junit.Test)

Example 33 with Collection

use of org.hibernate.mapping.Collection in project hibernate-orm by hibernate.

the class InFlightMetadataCollectorImpl method processCachingOverrides.

private void processCachingOverrides() {
    if (options.getCacheRegionDefinitions() == null) {
        return;
    }
    for (CacheRegionDefinition cacheRegionDefinition : options.getCacheRegionDefinitions()) {
        if (cacheRegionDefinition.getRegionType() == CacheRegionDefinition.CacheRegionType.ENTITY) {
            final PersistentClass entityBinding = getEntityBinding(cacheRegionDefinition.getRole());
            if (entityBinding == null) {
                throw new HibernateException("Cache override referenced an unknown entity : " + cacheRegionDefinition.getRole());
            }
            if (!RootClass.class.isInstance(entityBinding)) {
                throw new HibernateException("Cache override referenced a non-root entity : " + cacheRegionDefinition.getRole());
            }
            ((RootClass) entityBinding).setCacheRegionName(cacheRegionDefinition.getRegion());
            ((RootClass) entityBinding).setCacheConcurrencyStrategy(cacheRegionDefinition.getUsage());
            ((RootClass) entityBinding).setLazyPropertiesCacheable(cacheRegionDefinition.isCacheLazy());
        } else if (cacheRegionDefinition.getRegionType() == CacheRegionDefinition.CacheRegionType.COLLECTION) {
            final Collection collectionBinding = getCollectionBinding(cacheRegionDefinition.getRole());
            if (collectionBinding == null) {
                throw new HibernateException("Cache override referenced an unknown collection role : " + cacheRegionDefinition.getRole());
            }
            collectionBinding.setCacheRegionName(cacheRegionDefinition.getRegion());
            collectionBinding.setCacheConcurrencyStrategy(cacheRegionDefinition.getUsage());
        }
    }
}
Also used : RootClass(org.hibernate.mapping.RootClass) HibernateException(org.hibernate.HibernateException) CacheRegionDefinition(org.hibernate.boot.CacheRegionDefinition) Collection(org.hibernate.mapping.Collection) IdentifierCollection(org.hibernate.mapping.IdentifierCollection) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 34 with Collection

use of org.hibernate.mapping.Collection 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());
    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 EntityRegionAccessStrategy accessStrategy = sessionFactory.getCache().determineEntityRegionAccessStrategy(model);
        final NaturalIdRegionAccessStrategy naturalIdAccessStrategy = sessionFactory.getCache().determineNaturalIdRegionAccessStrategy(model);
        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 CollectionRegionAccessStrategy accessStrategy = sessionFactory.getCache().determineCollectionRegionAccessStrategy(model);
        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) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) NaturalIdRegionAccessStrategy(org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy) PersisterCreationContext(org.hibernate.persister.spi.PersisterCreationContext) 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) Collection(org.hibernate.mapping.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 35 with Collection

use of org.hibernate.mapping.Collection in project hibernate-orm by hibernate.

the class NestedEmbeddableMetadataTest method testEnumTypeInterpretation.

@Test
public void testEnumTypeInterpretation() {
    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().enableAutoClose().applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop").build();
    try {
        final Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(Customer.class).buildMetadata();
        PersistentClass classMetadata = metadata.getEntityBinding(Customer.class.getName());
        Property investmentsProperty = classMetadata.getProperty("investments");
        Collection investmentsValue = (Collection) investmentsProperty.getValue();
        Component investmentMetadata = (Component) investmentsValue.getElement();
        Value descriptionValue = investmentMetadata.getProperty("description").getValue();
        assertEquals(1, descriptionValue.getColumnSpan());
        Column selectable = (Column) descriptionValue.getColumnIterator().next();
        assertEquals(500, selectable.getLength());
        Component amountMetadata = (Component) investmentMetadata.getProperty("amount").getValue();
        SimpleValue currencyMetadata = (SimpleValue) amountMetadata.getProperty("currency").getValue();
        CustomType currencyType = (CustomType) currencyMetadata.getType();
        int[] currencySqlTypes = currencyType.sqlTypes(metadata);
        assertEquals(1, currencySqlTypes.length);
        assertJdbcTypeCode(Types.VARCHAR, currencySqlTypes[0]);
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
}
Also used : CustomType(org.hibernate.type.CustomType) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) SimpleValue(org.hibernate.mapping.SimpleValue) Column(org.hibernate.mapping.Column) SimpleValue(org.hibernate.mapping.SimpleValue) Value(org.hibernate.mapping.Value) Collection(org.hibernate.mapping.Collection) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Aggregations

Collection (org.hibernate.mapping.Collection)42 PersistentClass (org.hibernate.mapping.PersistentClass)19 Test (org.junit.Test)15 Property (org.hibernate.mapping.Property)11 Metadata (org.hibernate.boot.Metadata)9 MetadataSources (org.hibernate.boot.MetadataSources)9 Column (org.hibernate.mapping.Column)9 Iterator (java.util.Iterator)7 Component (org.hibernate.mapping.Component)7 RootClass (org.hibernate.mapping.RootClass)6 AnnotationException (org.hibernate.AnnotationException)5 SimpleValue (org.hibernate.mapping.SimpleValue)5 TestForIssue (org.hibernate.testing.TestForIssue)5 List (java.util.List)4 Map (java.util.Map)4 ElementCollection (javax.persistence.ElementCollection)4 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)4 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)4 Value (org.hibernate.mapping.Value)4 ArrayList (java.util.ArrayList)3