Search in sources :

Example 16 with ManyToOneType

use of org.hibernate.type.ManyToOneType in project hibernate-orm by hibernate.

the class ASTParserLoadingTest method testSelectClauseImplicitJoinWithIterate.

@Test
@SuppressWarnings({ "unchecked" })
public void testSelectClauseImplicitJoinWithIterate() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Zoo zoo = new Zoo();
    zoo.setName("The Zoo");
    zoo.setMammals(new HashMap());
    zoo.setAnimals(new HashMap());
    Mammal plat = new Mammal();
    plat.setBodyWeight(11f);
    plat.setDescription("Platypus");
    plat.setZoo(zoo);
    plat.setSerialNumber("plat123");
    zoo.getMammals().put("Platypus", plat);
    zoo.getAnimals().put("plat123", plat);
    s.persist(plat);
    s.persist(zoo);
    s.flush();
    s.clear();
    Query q = s.createQuery("select distinct a.zoo from Animal a where a.zoo is not null");
    Type type = q.getReturnTypes()[0];
    assertTrue(type instanceof ManyToOneType);
    assertEquals(((ManyToOneType) type).getAssociatedEntityName(), "org.hibernate.test.hql.Zoo");
    zoo = (Zoo) q.iterate().next();
    assertEquals(zoo.getMammals().size(), 1);
    assertEquals(zoo.getAnimals().size(), 1);
    s.clear();
    s.delete(plat);
    s.delete(zoo);
    t.commit();
    s.close();
}
Also used : DiscriminatorType(org.hibernate.persister.entity.DiscriminatorType) ManyToOneType(org.hibernate.type.ManyToOneType) ComponentType(org.hibernate.type.ComponentType) Type(org.hibernate.type.Type) Transaction(org.hibernate.Transaction) TransactionUtil2.inTransaction(org.hibernate.testing.transaction.TransactionUtil2.inTransaction) Query(org.hibernate.Query) HashMap(java.util.HashMap) ManyToOneType(org.hibernate.type.ManyToOneType) Session(org.hibernate.Session) Test(org.junit.Test)

Example 17 with ManyToOneType

use of org.hibernate.type.ManyToOneType in project hibernate-orm by hibernate.

the class CollectionMetadataGenerator method addValueToMiddleTable.

/**
 * @param value Value, which should be mapped to the middle-table, either as a relation to another entity,
 * or as a simple value.
 * @param xmlMapping If not <code>null</code>, xml mapping for this value is added to this element.
 * @param queryGeneratorBuilder In case <code>value</code> is a relation to another entity, information about it
 * should be added to the given.
 * @param prefix Prefix for proeprty names of related entities identifiers.
 * @param joinColumns Names of columns to use in the xml mapping, if this array isn't null and has any elements.
 *
 * @return Data for mapping this component.
 */
@SuppressWarnings({ "unchecked" })
private MiddleComponentData addValueToMiddleTable(Value value, Element xmlMapping, QueryGeneratorBuilder queryGeneratorBuilder, String prefix, JoinColumn[] joinColumns, boolean key) {
    final Type type = value.getType();
    if (type instanceof ManyToOneType) {
        final String prefixRelated = prefix + "_";
        final String referencedEntityName = MappingTools.getReferencedEntityName(value);
        final IdMappingData referencedIdMapping = mainGenerator.getReferencedIdMappingData(referencingEntityName, referencedEntityName, propertyAuditingData, true);
        // relation isn't inverse (so when <code>xmlMapping</code> is not null).
        if (xmlMapping != null) {
            addRelatedToXmlMapping(xmlMapping, prefixRelated, joinColumns != null && joinColumns.length > 0 ? MetadataTools.getColumnNameIterator(joinColumns) : MetadataTools.getColumnNameIterator(value.getColumnIterator()), referencedIdMapping);
        }
        // Storing the id data of the referenced entity: original mapper, prefixed mapper and entity name.
        final MiddleIdData referencedIdData = createMiddleIdData(referencedIdMapping, prefixRelated, referencedEntityName);
        // And adding it to the generator builder.
        queryGeneratorBuilder.addRelation(referencedIdData);
        return new MiddleComponentData(new MiddleRelatedComponentMapper(referencedIdData), queryGeneratorBuilder.getCurrentIndex());
    } else if (type instanceof ComponentType) {
        // Collection of embeddable elements.
        final Component component = (Component) value;
        final Class componentClass = ReflectionTools.loadClass(component.getComponentClassName(), mainGenerator.getClassLoaderService());
        final MiddleEmbeddableComponentMapper componentMapper = new MiddleEmbeddableComponentMapper(new MultiPropertyMapper(), componentClass);
        final Element parentXmlMapping = xmlMapping.getParent();
        final ComponentAuditingData auditData = new ComponentAuditingData();
        final ReflectionManager reflectionManager = mainGenerator.getMetadata().getMetadataBuildingOptions().getReflectionManager();
        new ComponentAuditedPropertiesReader(ModificationStore.FULL, new AuditedPropertiesReader.ComponentPropertiesSource(reflectionManager, component), auditData, mainGenerator.getGlobalCfg(), reflectionManager, "").read();
        // Emulating first pass.
        for (String auditedPropertyName : auditData.getPropertyNames()) {
            final PropertyAuditingData nestedAuditingData = auditData.getPropertyAuditingData(auditedPropertyName);
            mainGenerator.addValue(parentXmlMapping, component.getProperty(auditedPropertyName).getValue(), componentMapper, prefix, xmlMappingData, nestedAuditingData, true, true, true);
        }
        // Emulating second pass so that the relations can be mapped too.
        for (String auditedPropertyName : auditData.getPropertyNames()) {
            final PropertyAuditingData nestedAuditingData = auditData.getPropertyAuditingData(auditedPropertyName);
            mainGenerator.addValue(parentXmlMapping, component.getProperty(auditedPropertyName).getValue(), componentMapper, referencingEntityName, xmlMappingData, nestedAuditingData, true, false, true);
        }
        // Embeddable properties may contain null values, so cannot be stored within composite primary key.
        if (propertyValue.isSet()) {
            final String setOrdinalPropertyName = mainGenerator.getVerEntCfg().getEmbeddableSetOrdinalPropertyName();
            final Element ordinalProperty = MetadataTools.addProperty(xmlMapping, setOrdinalPropertyName, "integer", true, true);
            MetadataTools.addColumn(ordinalProperty, setOrdinalPropertyName, null, null, null, null, null, null, false);
        }
        return new MiddleComponentData(componentMapper, 0);
    } else {
        // Last but one parameter: collection components are always insertable
        final boolean mapped = mainGenerator.getBasicMetadataGenerator().addBasic(key ? xmlMapping : xmlMapping.getParent(), new PropertyAuditingData(prefix, "field", ModificationStore.FULL, RelationTargetAuditMode.AUDITED, null, null, false), value, null, true, key);
        if (mapped && key) {
            // Simple values are always stored in the first item of the array returned by the query generator.
            return new MiddleComponentData(new MiddleSimpleComponentMapper(mainGenerator.getVerEntCfg(), prefix), 0);
        } else if (mapped && !key) {
            // when mapped but not part of the key, its stored as a dummy mapper??
            return new MiddleComponentData(new MiddleMapElementNotKeyComponentMapper(mainGenerator.getVerEntCfg(), prefix), 0);
        } else {
            mainGenerator.throwUnsupportedTypeException(type, referencingEntityName, propertyName);
            // Impossible to get here.
            throw new AssertionError();
        }
    }
}
Also used : AuditedPropertiesReader(org.hibernate.envers.configuration.internal.metadata.reader.AuditedPropertiesReader) ComponentAuditedPropertiesReader(org.hibernate.envers.configuration.internal.metadata.reader.ComponentAuditedPropertiesReader) ComponentType(org.hibernate.type.ComponentType) ManyToOneType(org.hibernate.type.ManyToOneType) ReflectionManager(org.hibernate.annotations.common.reflection.ReflectionManager) MiddleSimpleComponentMapper(org.hibernate.envers.internal.entities.mapper.relation.component.MiddleSimpleComponentMapper) MiddleRelatedComponentMapper(org.hibernate.envers.internal.entities.mapper.relation.component.MiddleRelatedComponentMapper) Element(org.dom4j.Element) MultiPropertyMapper(org.hibernate.envers.internal.entities.mapper.MultiPropertyMapper) PropertyAuditingData(org.hibernate.envers.configuration.internal.metadata.reader.PropertyAuditingData) MiddleMapElementNotKeyComponentMapper(org.hibernate.envers.internal.entities.mapper.relation.component.MiddleMapElementNotKeyComponentMapper) ListType(org.hibernate.type.ListType) ManyToOneType(org.hibernate.type.ManyToOneType) MaterializedNClobType(org.hibernate.type.MaterializedNClobType) SetType(org.hibernate.type.SetType) MaterializedClobType(org.hibernate.type.MaterializedClobType) MapType(org.hibernate.type.MapType) ComponentType(org.hibernate.type.ComponentType) SortedSetType(org.hibernate.type.SortedSetType) SortedMapType(org.hibernate.type.SortedMapType) BagType(org.hibernate.type.BagType) Type(org.hibernate.type.Type) ComponentAuditingData(org.hibernate.envers.configuration.internal.metadata.reader.ComponentAuditingData) MiddleIdData(org.hibernate.envers.internal.entities.mapper.relation.MiddleIdData) ComponentAuditedPropertiesReader(org.hibernate.envers.configuration.internal.metadata.reader.ComponentAuditedPropertiesReader) MiddleEmbeddableComponentMapper(org.hibernate.envers.internal.entities.mapper.relation.component.MiddleEmbeddableComponentMapper) PersistentClass(org.hibernate.mapping.PersistentClass) MiddleComponentData(org.hibernate.envers.internal.entities.mapper.relation.MiddleComponentData) Component(org.hibernate.mapping.Component) IdMappingData(org.hibernate.envers.internal.entities.IdMappingData)

Example 18 with ManyToOneType

use of org.hibernate.type.ManyToOneType in project dhis2-core by dhis2.

the class HibernatePropertyIntrospector method createProperty.

private Property createProperty(Class<?> klass, org.hibernate.mapping.Property hibernateProperty, MetamodelImplementor metamodelImplementor) {
    Property property = new Property(klass);
    property.setRequired(false);
    property.setPersisted(true);
    property.setWritable(true);
    property.setOwner(true);
    Type type = hibernateProperty.getType();
    property.setName(hibernateProperty.getName());
    property.setFieldName(hibernateProperty.getName());
    property.setCascade(hibernateProperty.getCascade());
    property.setCollection(type.isCollectionType());
    property.setSetterMethod(hibernateProperty.getSetter(klass).getMethod());
    property.setGetterMethod(hibernateProperty.getGetter(klass).getMethod());
    if (property.isCollection()) {
        initCollectionProperty(metamodelImplementor, property, (CollectionType) type);
    }
    if (type instanceof SingleColumnType || type instanceof CustomType || type instanceof ManyToOneType) {
        Column column = (Column) hibernateProperty.getColumnIterator().next();
        property.setUnique(column.isUnique());
        property.setRequired(!column.isNullable());
        property.setMin(0d);
        property.setMax((double) column.getLength());
        property.setLength(column.getLength());
        if (type instanceof TextType) {
            property.setMin(0d);
            property.setMax((double) Integer.MAX_VALUE);
            property.setLength(Integer.MAX_VALUE);
        } else if (type instanceof IntegerType) {
            property.setMin((double) Integer.MIN_VALUE);
            property.setMax((double) Integer.MAX_VALUE);
            property.setLength(Integer.MAX_VALUE);
        } else if (type instanceof LongType) {
            property.setMin((double) Long.MIN_VALUE);
            property.setMax((double) Long.MAX_VALUE);
            property.setLength(Integer.MAX_VALUE);
        } else if (type instanceof DoubleType) {
            property.setMin(-Double.MAX_VALUE);
            property.setMax(Double.MAX_VALUE);
            property.setLength(Integer.MAX_VALUE);
        }
    }
    if (type instanceof ManyToOneType) {
        property.setManyToOne(true);
        property.setRequired(property.isRequired() && !property.isCollection());
        if (property.isOwner()) {
            property.setOwningRole(klass.getName() + "." + property.getName());
        } else {
            property.setInverseRole(klass.getName() + "." + property.getName());
        }
    } else if (type instanceof OneToOneType) {
        property.setOneToOne(true);
    } else if (type instanceof OneToMany) {
        property.setOneToMany(true);
    }
    return property;
}
Also used : CustomType(org.hibernate.type.CustomType) IntegerType(org.hibernate.type.IntegerType) CustomType(org.hibernate.type.CustomType) CollectionType(org.hibernate.type.CollectionType) ManyToOneType(org.hibernate.type.ManyToOneType) IntegerType(org.hibernate.type.IntegerType) TextType(org.hibernate.type.TextType) LongType(org.hibernate.type.LongType) SingleColumnType(org.hibernate.type.SingleColumnType) OneToOneType(org.hibernate.type.OneToOneType) SetType(org.hibernate.type.SetType) DoubleType(org.hibernate.type.DoubleType) Type(org.hibernate.type.Type) LongType(org.hibernate.type.LongType) SingleColumnType(org.hibernate.type.SingleColumnType) ManyToOneType(org.hibernate.type.ManyToOneType) Column(org.hibernate.mapping.Column) DoubleType(org.hibernate.type.DoubleType) OneToMany(org.hibernate.mapping.OneToMany) Property(org.hisp.dhis.schema.Property) TextType(org.hibernate.type.TextType) OneToOneType(org.hibernate.type.OneToOneType)

Example 19 with ManyToOneType

use of org.hibernate.type.ManyToOneType in project midpoint by Evolveum.

the class MidpointPersisterUtil method killUnwantedAssociationValues.

private static void killUnwantedAssociationValues(String[] propertyNames, Type[] propertyTypes, Object[] values, int depth) {
    if (values == null) {
        return;
    }
    for (int i = 0; i < propertyTypes.length; i++) {
        String name = propertyNames[i];
        Type type = propertyTypes[i];
        Object value = values[i];
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("{}- killUnwantedAssociationValues processing #{}: {} (type={}, value={})", StringUtils.repeat("  ", depth), i, name, type, value);
        }
        if (type instanceof ComponentType) {
            ComponentType componentType = (ComponentType) type;
            killUnwantedAssociationValues(componentType.getPropertyNames(), componentType.getSubtypes(), (Object[]) value, depth + 1);
        } else if (type instanceof ManyToOneType) {
            if (ASSOCIATION_TO_REMOVE.equals(name)) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("{}- killUnwantedAssociationValues KILLED #{}: {} (type={}, value={})", StringUtils.repeat("  ", depth), i, name, type, value);
                }
                values[i] = null;
            }
        }
    }
}
Also used : ManyToOneType(org.hibernate.type.ManyToOneType) ComponentType(org.hibernate.type.ComponentType) Type(org.hibernate.type.Type) ComponentType(org.hibernate.type.ComponentType) ManyToOneType(org.hibernate.type.ManyToOneType)

Example 20 with ManyToOneType

use of org.hibernate.type.ManyToOneType in project hibernate-orm by hibernate.

the class IdMetadataGenerator method addIdProperties.

@SuppressWarnings({ "unchecked" })
private boolean addIdProperties(Element parent, Iterator<Property> properties, SimpleMapperBuilder mapper, boolean key, boolean audited) {
    while (properties.hasNext()) {
        final Property property = properties.next();
        final Type propertyType = property.getType();
        if (!"_identifierMapper".equals(property.getName())) {
            boolean added = false;
            if (propertyType instanceof ManyToOneType) {
                added = mainGenerator.getBasicMetadataGenerator().addManyToOne(parent, getIdPersistentPropertyAuditingData(property), property.getValue(), mapper);
            } else {
                // Last but one parameter: ids are always insertable
                added = mainGenerator.getBasicMetadataGenerator().addBasic(parent, getIdPersistentPropertyAuditingData(property), property.getValue(), mapper, true, key);
            }
            if (!added) {
                // target relation mode not audited.
                if (audited) {
                    throw new MappingException("Type not supported: " + propertyType.getClass().getName());
                } else {
                    return false;
                }
            }
        }
    }
    return true;
}
Also used : ManyToOneType(org.hibernate.type.ManyToOneType) Type(org.hibernate.type.Type) ManyToOneType(org.hibernate.type.ManyToOneType) Property(org.hibernate.mapping.Property) MappingException(org.hibernate.MappingException)

Aggregations

ManyToOneType (org.hibernate.type.ManyToOneType)35 Test (org.junit.Test)28 ClassType (org.hibernate.type.ClassType)24 EntityType (org.hibernate.type.EntityType)24 IType (org.jboss.tools.hibernate.runtime.spi.IType)24 OneToOneType (org.hibernate.type.OneToOneType)11 Type (org.hibernate.type.Type)9 ComponentType (org.hibernate.type.ComponentType)7 HashMap (java.util.HashMap)4 Query (org.hibernate.Query)4 Session (org.hibernate.Session)4 Transaction (org.hibernate.Transaction)4 DiscriminatorType (org.hibernate.persister.entity.DiscriminatorType)4 TransactionUtil2.inTransaction (org.hibernate.testing.transaction.TransactionUtil2.inTransaction)4 ArrayList (java.util.ArrayList)2 List (java.util.List)2 PersistentClass (org.hibernate.mapping.PersistentClass)2 CollectionType (org.hibernate.type.CollectionType)2 SetType (org.hibernate.type.SetType)2 Element (org.dom4j.Element)1