List of usage examples for org.hibernate.mapping ManyToOne ManyToOne
public ManyToOne(MetadataBuildingContext buildingContext, Table table)
From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java
License:Open Source License
protected void createM2O(Configuration config, Mappings mappings, ForeignKey relationship) { com.manydesigns.portofino.model.database.Table manyMDTable = relationship.getFromTable(); com.manydesigns.portofino.model.database.Table oneMDTable = relationship.getToTable(); String manyMDQualifiedTableName = manyMDTable.getActualEntityName(); String oneMDQualifiedTableName = oneMDTable.getActualEntityName(); RootClass clazz = (RootClass) mappings.getClass(manyMDQualifiedTableName); if (clazz == null) { logger.error("Cannot find table '{}' as 'many' side of foreign key '{}'. Skipping relationship.", manyMDQualifiedTableName, relationship.getName()); return;/*from w ww. j av a 2 s. c om*/ } Table tab = clazz.getTable(); List<String> columnNames = new ArrayList<String>(); for (Reference ref : relationship.getReferences()) { if (ref.getActualFromColumn() == null) { logger.error("Missing from column {}, skipping relationship", ref.getFromColumn()); return; } columnNames.add(ref.getFromColumn()); } ManyToOne m2o = new ManyToOne(mappings, tab); m2o.setLazy(LAZY); final HashMap<String, PersistentClass> persistentClasses = new HashMap<String, PersistentClass>(); persistentClasses.put(oneMDQualifiedTableName, config.getClassMapping(oneMDQualifiedTableName)); m2o.setReferencedEntityName(oneMDQualifiedTableName); m2o.createPropertyRefConstraints(persistentClasses); PersistentClass manyClass = config.getClassMapping(manyMDQualifiedTableName); for (String columnName : columnNames) { Column col = new Column(); col.setName(escapeName(columnName)); //Recupero la colonna precedentemente associata alla tabella: //essa ha uno uniqueIdentifier generato al momento dell'associazione alla tabella; //questo viene utilizzato per disambiguare l'alias della colonna nelle query //SQL generate da Hibernate. col = manyClass.getTable().getColumn(col); if (col == null) { logger.error("Column not found in 'many' entity {}: {}, " + "skipping relationship", manyClass.getEntityName(), columnName); return; } m2o.addColumn(col); } Property prop = new Property(); prop.setName(relationship.getActualOnePropertyName()); //prop.setNodeName(relationship.getActualOnePropertyName()); prop.setValue(m2o); prop.setCascade("none"); //TODO era "all", capire prop.setInsertable(false); prop.setUpdateable(false); clazz.addProperty(prop); }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java
License:Apache License
protected void bindCollectionSecondPass(GrailsDomainClassProperty property, Mappings mappings, Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) { PersistentClass associatedClass = null; if (LOG.isDebugEnabled()) LOG.debug("Mapping collection: " + collection.getRole() + " -> " + collection.getCollectionTable().getName()); PropertyConfig propConfig = getPropertyConfig(property); if (propConfig != null && StringUtils.hasText(propConfig.getSort())) { if (!property.isBidirectional() && property.isOneToMany()) { throw new GrailsDomainException("Default sort for associations [" + property.getDomainClass().getName() + "->" + property.getName() + "] are not supported with unidirectional one to many relationships."); }//from w ww.ja v a 2s. co m GrailsDomainClass referenced = property.getReferencedDomainClass(); if (referenced != null) { GrailsDomainClassProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort()); String associatedClassName = property.getReferencedDomainClass().getFullName(); associatedClass = (PersistentClass) persistentClasses.get(associatedClassName); if (associatedClass != null) { collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass, collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc")); } } } // Configure one-to-many if (collection.isOneToMany()) { GrailsDomainClass referenced = property.getReferencedDomainClass(); Mapping m = getRootMapping(referenced); boolean tablePerSubclass = m != null && !m.getTablePerHierarchy(); if (referenced != null && !referenced.isRoot() && !tablePerSubclass) { Mapping rootMapping = getRootMapping(referenced); String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME; if (rootMapping != null) { final ColumnConfig discriminatorColumn = rootMapping.getDiscriminatorColumn(); if (discriminatorColumn != null) { discriminatorColumnName = discriminatorColumn.getName(); } if (rootMapping.getDiscriminatorMap().get("formula") != null) { discriminatorColumnName = (String) m.getDiscriminatorMap().get("formula"); } } //NOTE: this will build the set for the in clause if it has sublcasses Set<String> discSet = buildDiscriminatorSet(referenced); String inclause = DefaultGroovyMethods.join(discSet, ","); collection.setWhere(discriminatorColumnName + " in (" + inclause + ")"); } OneToMany oneToMany = (OneToMany) collection.getElement(); String associatedClassName = oneToMany.getReferencedEntityName(); associatedClass = (PersistentClass) persistentClasses.get(associatedClassName); // if there is no persistent class for the association throw exception if (associatedClass == null) { throw new MappingException( "Association references unmapped class: " + oneToMany.getReferencedEntityName()); } oneToMany.setAssociatedClass(associatedClass); if (shouldBindCollectionWithForeignKey(property)) { collection.setCollectionTable(associatedClass.getTable()); } bindCollectionForPropertyConfig(collection, propConfig); } if (isSorted(property)) { collection.setSorted(true); } // setup the primary key references DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses); // link a bidirectional relationship if (property.isBidirectional()) { GrailsDomainClassProperty otherSide = property.getOtherSide(); if (otherSide.isManyToOne() && shouldBindCollectionWithForeignKey(property)) { linkBidirectionalOneToMany(collection, associatedClass, key, otherSide); } else if (property.isManyToMany() || Map.class.isAssignableFrom(property.getType())) { bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName); } } else { if (hasJoinKeyMapping(propConfig)) { bindSimpleValue("long", key, false, propConfig.getJoinTable().getKey().getName(), mappings); } else { bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName); } } collection.setKey(key); // get cache config if (propConfig != null) { CacheConfig cacheConfig = propConfig.getCache(); if (cacheConfig != null) { collection.setCacheConcurrencyStrategy(cacheConfig.getUsage()); } } // if we have a many-to-many if (property.isManyToMany() || isBidirectionalOneToManyMap(property)) { GrailsDomainClassProperty otherSide = property.getOtherSide(); if (property.isBidirectional()) { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getDomainClass().getName() + "." + otherSide.getName() + " -> " + collection.getCollectionTable().getName() + " as ManyToOne"); ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable()); bindManyToMany(otherSide, element, mappings, sessionFactoryBeanName); collection.setElement(element); bindCollectionForPropertyConfig(collection, propConfig); if (property.isCircular()) { collection.setInverse(false); } } else { // TODO support unidirectional many-to-many } } else if (shouldCollectionBindWithJoinColumn(property)) { bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName); } else if (isUnidirectionalOneToMany(property)) { // for non-inverse one-to-many, with a not-null fk, add a backref! // there are problems with list and map mappings and join columns relating to duplicate key constraints // TODO change this when HHH-1268 is resolved bindUnidirectionalOneToMany(property, mappings, collection); } }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java
License:Apache License
protected void bindCollectionWithJoinTable(GrailsDomainClassProperty property, Mappings mappings, Collection collection, PropertyConfig config, String sessionFactoryBeanName) { NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); SimpleValue element;/*from w w w .j a v a 2 s . c o m*/ if (property.isBasicCollectionType()) { element = new SimpleValue(mappings, collection.getCollectionTable()); } else { // for a normal unidirectional one-to-many we use a join column element = new ManyToOne(mappings, collection.getCollectionTable()); bindUnidirectionalOneToManyInverseValues(property, (ManyToOne) element); } collection.setInverse(false); String columnName; final boolean hasJoinColumnMapping = hasJoinColumnMapping(config); if (property.isBasicCollectionType()) { final Class<?> referencedType = property.getReferencedPropertyType(); String className = referencedType.getName(); final boolean isEnum = referencedType.isEnum(); if (hasJoinColumnMapping) { columnName = config.getJoinTable().getColumn().getName(); } else { columnName = isEnum ? namingStrategy.propertyToColumnName(className) : addUnderscore(namingStrategy.propertyToColumnName(property.getName()), namingStrategy.propertyToColumnName(className)); } if (isEnum) { bindEnumType(property, referencedType, element, columnName); } else { String typeName = getTypeName(property, config, getMapping(property.getDomainClass())); if (typeName == null) { Type type = mappings.getTypeResolver().basic(className); if (type != null) { typeName = type.getName(); } } if (typeName == null) { String domainName = property.getDomainClass().getName(); throw new MappingException("Missing type or column for column[" + columnName + "] on domain[" + domainName + "] referencing[" + className + "]"); } bindSimpleValue(typeName, element, true, columnName, mappings); if (hasJoinColumnMapping) { bindColumnConfigToColumn(getColumnForSimpleValue(element), config.getJoinTable().getColumn()); } } } else { final GrailsDomainClass domainClass = property.getReferencedDomainClass(); Mapping m = getMapping(domainClass.getClazz()); if (hasCompositeIdentifier(m)) { CompositeIdentity ci = (CompositeIdentity) m.getIdentity(); bindCompositeIdentifierToManyToOne(property, element, ci, domainClass, EMPTY_PATH, sessionFactoryBeanName); } else { if (hasJoinColumnMapping) { columnName = config.getJoinTable().getColumn().getName(); } else { columnName = namingStrategy.propertyToColumnName(domainClass.getPropertyName()) + FOREIGN_KEY_SUFFIX; } bindSimpleValue("long", element, true, columnName, mappings); } } collection.setElement(element); bindCollectionForPropertyConfig(collection, config); }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java
License:Apache License
/** * Creates and binds the properties for the specified Grails domain class and PersistentClass * and binds them to the Hibernate runtime meta model * * @param domainClass The Grails domain class * @param persistentClass The Hibernate PersistentClass instance * @param mappings The Hibernate Mappings instance * @param sessionFactoryBeanName the session factory bean name *//*from ww w . j av a 2 s. c o m*/ protected void createClassProperties(GrailsDomainClass domainClass, PersistentClass persistentClass, Mappings mappings, String sessionFactoryBeanName) { GrailsDomainClassProperty[] persistentProperties = domainClass.getPersistentProperties(); Table table = persistentClass.getTable(); Mapping gormMapping = getMapping(domainClass.getClazz()); if (gormMapping != null) { table.setComment(gormMapping.getComment()); } for (GrailsDomainClassProperty currentGrailsProp : persistentProperties) { // if its inherited skip boolean isBidirectionalManyToOne = isBidirectionalManyToOne(currentGrailsProp); if (currentGrailsProp.isInherited()) { continue; } if (currentGrailsProp.isInherited() && isBidirectionalManyToOne && currentGrailsProp.isCircular()) { continue; } if (isCompositeIdProperty(gormMapping, currentGrailsProp)) continue; if (isIdentityProperty(gormMapping, currentGrailsProp)) continue; if (LOG.isDebugEnabled()) { LOG.debug("[GrailsDomainBinder] Binding persistent property [" + currentGrailsProp.getName() + "]"); } Value value = null; // see if it's a collection type CollectionType collectionType = CT.collectionTypeForClass(currentGrailsProp.getType()); Class<?> userType = getUserType(currentGrailsProp); if (userType != null) { if (LOG.isDebugEnabled()) { LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); } value = new SimpleValue(mappings, table); bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings, sessionFactoryBeanName); } else if (collectionType != null) { String typeName = getTypeName(currentGrailsProp, getPropertyConfig(currentGrailsProp), gormMapping); if ("serializable".equals(typeName)) { value = new SimpleValue(mappings, table); bindSimpleValue(typeName, (SimpleValue) value, currentGrailsProp.isOptional(), getColumnNameForPropertyAndPath(currentGrailsProp, EMPTY_PATH, null, sessionFactoryBeanName), mappings); } else { // create collection Collection collection = collectionType.create(currentGrailsProp, persistentClass, EMPTY_PATH, mappings, sessionFactoryBeanName); mappings.addCollection(collection); value = collection; } } else if (currentGrailsProp.isEnum()) { value = new SimpleValue(mappings, table); bindEnumType(currentGrailsProp, (SimpleValue) value, EMPTY_PATH, sessionFactoryBeanName); } // work out what type of relationship it is and bind value else if (currentGrailsProp.isManyToOne()) { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as ManyToOne"); value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, sessionFactoryBeanName); } else if (currentGrailsProp.isOneToOne() && userType == null) { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as OneToOne"); if (currentGrailsProp.isHasOne() && !currentGrailsProp.isBidirectional()) { throw new MappingException("hasOne property [" + currentGrailsProp.getDomainClass().getName() + "." + currentGrailsProp.getName() + "] is not bidirectional. Specify the other side of the relationship!"); } else if (canBindOneToOneWithSingleColumnAndForeignKey(currentGrailsProp)) { value = new OneToOne(mappings, table, persistentClass); bindOneToOne(currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); } else { if (currentGrailsProp.isHasOne() && currentGrailsProp.isBidirectional()) { value = new OneToOne(mappings, table, persistentClass); bindOneToOne(currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); } else { value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, sessionFactoryBeanName); } } } else if (currentGrailsProp.isEmbedded()) { value = new Component(mappings, persistentClass); bindComponent((Component) value, currentGrailsProp, true, mappings, sessionFactoryBeanName); } else { if (LOG.isDebugEnabled()) { LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); } value = new SimpleValue(mappings, table); bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings, sessionFactoryBeanName); } if (value != null) { Property property = createProperty(value, persistentClass, currentGrailsProp, mappings); persistentClass.addProperty(property); } } bindNaturalIdentifier(table, gormMapping, persistentClass); }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java
License:Apache License
protected void bindComponentProperty(Component component, GrailsDomainClassProperty componentProperty, GrailsDomainClassProperty currentGrailsProp, PersistentClass persistentClass, String path, Table table, Mappings mappings, String sessionFactoryBeanName) { Value value;/* w w w. j av a 2 s. com*/ // see if it's a collection type CollectionType collectionType = CT.collectionTypeForClass(currentGrailsProp.getType()); if (collectionType != null) { // create collection Collection collection = collectionType.create(currentGrailsProp, persistentClass, path, mappings, sessionFactoryBeanName); mappings.addCollection(collection); value = collection; } // work out what type of relationship it is and bind value else if (currentGrailsProp.isManyToOne()) { if (LOG.isDebugEnabled()) LOG.debug( "[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as ManyToOne"); value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, path, mappings, sessionFactoryBeanName); } else if (currentGrailsProp.isOneToOne()) { if (LOG.isDebugEnabled()) LOG.debug( "[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as OneToOne"); if (canBindOneToOneWithSingleColumnAndForeignKey(currentGrailsProp)) { value = new OneToOne(mappings, table, persistentClass); bindOneToOne(currentGrailsProp, (OneToOne) value, path, sessionFactoryBeanName); } else { value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, path, mappings, sessionFactoryBeanName); } } else if (currentGrailsProp.isEmbedded()) { value = new Component(mappings, persistentClass); bindComponent((Component) value, currentGrailsProp, true, mappings, sessionFactoryBeanName); } else { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); value = new SimpleValue(mappings, table); if (currentGrailsProp.isEnum()) { bindEnumType(currentGrailsProp, (SimpleValue) value, path, sessionFactoryBeanName); } else { bindSimpleValue(currentGrailsProp, componentProperty, (SimpleValue) value, path, mappings, sessionFactoryBeanName); } } if (value != null) { Property persistentProperty = createProperty(value, persistentClass, currentGrailsProp, mappings); component.addProperty(persistentProperty); if (isComponentPropertyNullable(componentProperty)) { final Iterator<?> columnIterator = value.getColumnIterator(); while (columnIterator.hasNext()) { Column c = (Column) columnIterator.next(); c.setNullable(true); } } } }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder.java
License:Apache License
private static void bindCollectionSecondPass(GrailsDomainClassProperty property, Mappings mappings, Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) { PersistentClass associatedClass = null; if (LOG.isDebugEnabled()) LOG.debug("Mapping collection: " + collection.getRole() + " -> " + collection.getCollectionTable().getName()); PropertyConfig propConfig = getPropertyConfig(property); if (propConfig != null && !StringUtils.isBlank(propConfig.getSort())) { if (!property.isBidirectional() && property.isOneToMany()) { throw new GrailsDomainException("Default sort for associations [" + property.getDomainClass().getName() + "->" + property.getName() + "] are not supported with unidirectional one to many relationships."); }// w w w .j av a2 s .c o m GrailsDomainClass referenced = property.getReferencedDomainClass(); if (referenced != null) { GrailsDomainClassProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort()); String associatedClassName = property.getReferencedDomainClass().getFullName(); associatedClass = (PersistentClass) persistentClasses.get(associatedClassName); if (associatedClass != null) { collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass, collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc")); } } } // Configure one-to-many if (collection.isOneToMany()) { GrailsDomainClass referenced = property.getReferencedDomainClass(); Mapping m = getRootMapping(referenced); boolean tablePerSubclass = m != null && !m.getTablePerHierarchy(); if (referenced != null && !referenced.isRoot() && !tablePerSubclass) { Mapping rootMapping = getRootMapping(referenced); String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME; if (rootMapping != null) { final ColumnConfig discriminatorColumn = rootMapping.getDiscriminatorColumn(); if (discriminatorColumn != null) { discriminatorColumnName = discriminatorColumn.getName(); } if (rootMapping.getDiscriminatorMap().get("formula") != null) { discriminatorColumnName = (String) m.getDiscriminatorMap().get("formula"); } } //NOTE: this will build the set for the in clause if it has sublcasses Set<String> discSet = buildDiscriminatorSet(referenced); String inclause = StringUtils.join(discSet, ','); collection.setWhere(discriminatorColumnName + " in (" + inclause + ")"); } OneToMany oneToMany = (OneToMany) collection.getElement(); String associatedClassName = oneToMany.getReferencedEntityName(); associatedClass = (PersistentClass) persistentClasses.get(associatedClassName); // if there is no persistent class for the association throw exception if (associatedClass == null) { throw new MappingException( "Association references unmapped class: " + oneToMany.getReferencedEntityName()); } oneToMany.setAssociatedClass(associatedClass); if (shouldBindCollectionWithForeignKey(property)) { collection.setCollectionTable(associatedClass.getTable()); } bindCollectionForPropertyConfig(collection, propConfig); } if (isSorted(property)) { collection.setSorted(true); } // setup the primary key references DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses); // link a bidirectional relationship if (property.isBidirectional()) { GrailsDomainClassProperty otherSide = property.getOtherSide(); if (otherSide.isManyToOne() && shouldBindCollectionWithForeignKey(property)) { linkBidirectionalOneToMany(collection, associatedClass, key, otherSide); } else if (property.isManyToMany() || Map.class.isAssignableFrom(property.getType())) { bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName); } } else { if (hasJoinKeyMapping(propConfig)) { bindSimpleValue("long", key, false, propConfig.getJoinTable().getKey().getName(), mappings); } else { bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName); } } collection.setKey(key); // get cache config if (propConfig != null) { CacheConfig cacheConfig = propConfig.getCache(); if (cacheConfig != null) { collection.setCacheConcurrencyStrategy(cacheConfig.getUsage()); } } // if we have a many-to-many if (property.isManyToMany() || isBidirectionalOneToManyMap(property)) { GrailsDomainClassProperty otherSide = property.getOtherSide(); if (property.isBidirectional()) { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getDomainClass().getName() + "." + otherSide.getName() + " -> " + collection.getCollectionTable().getName() + " as ManyToOne"); ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable()); bindManyToMany(otherSide, element, mappings, sessionFactoryBeanName); collection.setElement(element); bindCollectionForPropertyConfig(collection, propConfig); if (property.isCircular()) { collection.setInverse(false); } } else { // TODO support unidirectional many-to-many } } else if (shouldCollectionBindWithJoinColumn(property)) { bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName); } else if (isUnidirectionalOneToMany(property)) { // for non-inverse one-to-many, with a not-null fk, add a backref! // there are problems with list and map mappings and join columns relating to duplicate key constraints // TODO change this when HHH-1268 is resolved bindUnidirectionalOneToMany(property, mappings, collection); } }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder.java
License:Apache License
private static void bindCollectionWithJoinTable(GrailsDomainClassProperty property, Mappings mappings, Collection collection, PropertyConfig config, String sessionFactoryBeanName) { NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); SimpleValue element;// w ww.java2 s . c o m if (property.isBasicCollectionType()) { element = new SimpleValue(mappings, collection.getCollectionTable()); } else { // for a normal unidirectional one-to-many we use a join column element = new ManyToOne(mappings, collection.getCollectionTable()); bindUnidirectionalOneToManyInverseValues(property, (ManyToOne) element); } collection.setInverse(false); String columnName; final boolean hasJoinColumnMapping = hasJoinColumnMapping(config); if (property.isBasicCollectionType()) { final Class<?> referencedType = property.getReferencedPropertyType(); String className = referencedType.getName(); final boolean isEnum = GrailsClassUtils.isJdk5Enum(referencedType); if (hasJoinColumnMapping) { columnName = config.getJoinTable().getColumn().getName(); } else { columnName = isEnum ? namingStrategy.propertyToColumnName(className) : addUnderscore(namingStrategy.propertyToColumnName(property.getName()), namingStrategy.propertyToColumnName(className)); } if (isEnum) { bindEnumType(property, referencedType, element, columnName); } else { String typeName = getTypeName(property, config, getMapping(property.getDomainClass())); if (typeName == null) { Type type = mappings.getTypeResolver().basic(className); if (type != null) { typeName = type.getName(); } } if (typeName == null) { String domainName = property.getDomainClass().getName(); throw new MappingException("Missing type or column for column[" + columnName + "] on domain[" + domainName + "] referencing[" + className + "]"); } bindSimpleValue(typeName, element, true, columnName, mappings); if (hasJoinColumnMapping) { bindColumnConfigToColumn(getColumnForSimpleValue(element), config.getJoinTable().getColumn()); } } } else { final GrailsDomainClass domainClass = property.getReferencedDomainClass(); Mapping m = getMapping(domainClass.getClazz()); if (hasCompositeIdentifier(m)) { CompositeIdentity ci = (CompositeIdentity) m.getIdentity(); bindCompositeIdentifierToManyToOne(property, element, ci, domainClass, EMPTY_PATH, sessionFactoryBeanName); } else { if (hasJoinColumnMapping) { columnName = config.getJoinTable().getColumn().getName(); } else { columnName = namingStrategy.propertyToColumnName(domainClass.getPropertyName()) + FOREIGN_KEY_SUFFIX; } bindSimpleValue("long", element, true, columnName, mappings); } } collection.setElement(element); bindCollectionForPropertyConfig(collection, config); }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder.java
License:Apache License
/** * Creates and binds the properties for the specified Grails domain class and PersistentClass * and binds them to the Hibernate runtime meta model * * @param domainClass The Grails domain class * @param persistentClass The Hibernate PersistentClass instance * @param mappings The Hibernate Mappings instance * @param sessionFactoryBeanName the session factory bean name *//* www .j a v a 2 s . c o m*/ protected static void createClassProperties(GrailsDomainClass domainClass, PersistentClass persistentClass, Mappings mappings, String sessionFactoryBeanName) { GrailsDomainClassProperty[] persistentProperties = domainClass.getPersistentProperties(); Table table = persistentClass.getTable(); Mapping gormMapping = getMapping(domainClass.getClazz()); for (GrailsDomainClassProperty currentGrailsProp : persistentProperties) { // if its inherited skip boolean isBidirectionalManyToOne = isBidirectionalManyToOne(currentGrailsProp); if (currentGrailsProp.isInherited()) { continue; } if (currentGrailsProp.isInherited() && isBidirectionalManyToOne && currentGrailsProp.isCircular()) { continue; } if (isCompositeIdProperty(gormMapping, currentGrailsProp)) continue; if (isIdentityProperty(gormMapping, currentGrailsProp)) continue; if (LOG.isDebugEnabled()) { LOG.debug("[GrailsDomainBinder] Binding persistent property [" + currentGrailsProp.getName() + "]"); } Value value = null; // see if it's a collection type CollectionType collectionType = CollectionType.collectionTypeForClass(currentGrailsProp.getType()); Class<?> userType = getUserType(currentGrailsProp); if (collectionType != null) { String typeName = getTypeName(currentGrailsProp, getPropertyConfig(currentGrailsProp), gormMapping); if (typeName != null && "serializable".equals(typeName)) { value = new SimpleValue(mappings, table); bindSimpleValue(typeName, (SimpleValue) value, currentGrailsProp.isOptional(), getColumnNameForPropertyAndPath(currentGrailsProp, EMPTY_PATH, null, sessionFactoryBeanName), mappings); } else { // create collection Collection collection = collectionType.create(currentGrailsProp, persistentClass, EMPTY_PATH, mappings, sessionFactoryBeanName); mappings.addCollection(collection); value = collection; } } else if (currentGrailsProp.isEnum()) { value = new SimpleValue(mappings, table); bindEnumType(currentGrailsProp, (SimpleValue) value, EMPTY_PATH, sessionFactoryBeanName); } // work out what type of relationship it is and bind value else if (currentGrailsProp.isManyToOne()) { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as ManyToOne"); value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, sessionFactoryBeanName); } else if (currentGrailsProp.isOneToOne() && userType == null) { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as OneToOne"); if (currentGrailsProp.isHasOne() && !currentGrailsProp.isBidirectional()) { throw new MappingException("hasOne property [" + currentGrailsProp.getDomainClass().getName() + "." + currentGrailsProp.getName() + "] is not bidirectional. Specify the other side of the relationship!"); } else if (canBindOneToOneWithSingleColumnAndForeignKey(currentGrailsProp)) { value = new OneToOne(mappings, table, persistentClass); bindOneToOne(currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); } else { if (currentGrailsProp.isHasOne() && currentGrailsProp.isBidirectional()) { value = new OneToOne(mappings, table, persistentClass); bindOneToOne(currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); } else { value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, sessionFactoryBeanName); } } } else if (currentGrailsProp.isEmbedded()) { value = new Component(mappings, persistentClass); bindComponent((Component) value, currentGrailsProp, true, mappings, sessionFactoryBeanName); } else { if (LOG.isDebugEnabled()) { LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); } value = new SimpleValue(mappings, table); bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings, sessionFactoryBeanName); } if (value != null) { Property property = createProperty(value, persistentClass, currentGrailsProp, mappings); persistentClass.addProperty(property); } } bindNaturalIdentifier(table, gormMapping, persistentClass); }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder.java
License:Apache License
private static void bindComponentProperty(Component component, GrailsDomainClassProperty componentProperty, GrailsDomainClassProperty currentGrailsProp, PersistentClass persistentClass, String path, Table table, Mappings mappings, String sessionFactoryBeanName) { Value value;/* ww w . j a v a2s . co m*/ // see if it's a collection type CollectionType collectionType = CollectionType.collectionTypeForClass(currentGrailsProp.getType()); if (collectionType != null) { // create collection Collection collection = collectionType.create(currentGrailsProp, persistentClass, path, mappings, sessionFactoryBeanName); mappings.addCollection(collection); value = collection; } // work out what type of relationship it is and bind value else if (currentGrailsProp.isManyToOne()) { if (LOG.isDebugEnabled()) LOG.debug( "[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as ManyToOne"); value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, path, mappings, sessionFactoryBeanName); } else if (currentGrailsProp.isOneToOne()) { if (LOG.isDebugEnabled()) LOG.debug( "[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as OneToOne"); if (canBindOneToOneWithSingleColumnAndForeignKey(currentGrailsProp)) { value = new OneToOne(mappings, table, persistentClass); bindOneToOne(currentGrailsProp, (OneToOne) value, path, sessionFactoryBeanName); } else { value = new ManyToOne(mappings, table); bindManyToOne(currentGrailsProp, (ManyToOne) value, path, mappings, sessionFactoryBeanName); } } else if (currentGrailsProp.isEmbedded()) { value = new Component(mappings, persistentClass); bindComponent((Component) value, currentGrailsProp, true, mappings, sessionFactoryBeanName); } else { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); value = new SimpleValue(mappings, table); if (currentGrailsProp.isEnum()) { bindEnumType(currentGrailsProp, (SimpleValue) value, path, sessionFactoryBeanName); } else { bindSimpleValue(currentGrailsProp, componentProperty, (SimpleValue) value, path, mappings, sessionFactoryBeanName); } } if (value != null) { Property persistentProperty = createProperty(value, persistentClass, currentGrailsProp, mappings); component.addProperty(persistentProperty); if (isComponentPropertyNullable(componentProperty)) { final Iterator<?> columnIterator = value.getColumnIterator(); while (columnIterator.hasNext()) { Column c = (Column) columnIterator.next(); c.setNullable(true); } } } }
From source file:org.eclipse.emf.teneo.hibernate.HbDataStore.java
License:Open Source License
/** * Extra lazy mapping for lists needs a real property for the list index and * a real inverse for the other side as well. * /*from w ww . ja va2s. co m*/ * This method iterates over all associations and adds an inverse for the * list and set mappings. */ protected void addExtraLazyInverseProperties() { final Map<String, PersistentClass> persistentClasses = new HashMap<String, PersistentClass>(); for (Iterator<?> pcs = getClassMappings(); pcs.hasNext();) { final PersistentClass pc = (PersistentClass) pcs.next(); if (isClassOrSuperClassEAVMapped(pc)) { continue; } persistentClasses.put(pc.getEntityName(), pc); } for (Iterator<?> pcs = getClassMappings(); pcs.hasNext();) { final PersistentClass pc = (PersistentClass) pcs.next(); // copy to prevent concurrent modification final Iterator<?> propIt = pc.getPropertyIterator(); final List<Property> props = new ArrayList<Property>(); while (propIt.hasNext()) { final Property prop = (Property) propIt.next(); props.add(prop); } for (Property prop : props) { EClass eClass = null; if (pc.getMetaAttribute(HbMapperConstants.FEATUREMAP_META) == null) { if (pc.getEntityName() != null) { eClass = getEntityNameStrategy().toEClass(pc.getEntityName()); } else { eClass = EModelResolver.instance().getEClass(pc.getMappedClass()); } } final EStructuralFeature ef = eClass == null ? null : StoreUtil.getEStructuralFeature(eClass, prop.getName()); if (ef != null && ef instanceof EReference && prop.getValue() instanceof Collection) { final Collection collection = (Collection) prop.getValue(); final EReference eReference = (EReference) ef; // only work for extra lazy if (!collection.isExtraLazy()) { continue; } final Value elementValue = collection.getElement(); final PersistentClass elementPC; if (elementValue instanceof OneToMany) { final OneToMany oneToMany = (OneToMany) elementValue; elementPC = oneToMany.getAssociatedClass(); } else if (elementValue instanceof ManyToOne) { final ManyToOne mto = (ManyToOne) elementValue; elementPC = persistentClasses.get(mto.getReferencedEntityName()); } else { continue; } if (isClassOrSuperClassEAVMapped(elementPC)) { continue; } collection.setInverse(true); // and add an eopposite if (eReference.getEOpposite() == null) { final Table collectionTable = collection.getCollectionTable(); if (isClassOrSuperClassEAVMapped(elementPC)) { continue; } final Property inverseRefProperty = new Property(); inverseRefProperty.setName(StoreUtil.getExtraLazyInversePropertyName(ef)); final Map<Object, Object> metas = new HashMap<Object, Object>(); final MetaAttribute metaAttribute = new MetaAttribute( HbConstants.SYNTHETIC_PROPERTY_INDICATOR); metaAttribute.addValue("true"); metas.put(HbConstants.SYNTHETIC_PROPERTY_INDICATOR, metaAttribute); inverseRefProperty.setMetaAttributes(metas); inverseRefProperty.setNodeName(inverseRefProperty.getName()); inverseRefProperty.setPropertyAccessorName(SyntheticPropertyHandler.class.getName()); inverseRefProperty.setLazy(false); final ManyToOne mto = new ManyToOne(getMappings(), collectionTable); mto.setReferencedEntityName(pc.getEntityName()); mto.setLazy(false); mto.setFetchMode(FetchMode.SELECT); inverseRefProperty.setValue(mto); final Iterator<?> it = collection.getKey().getColumnIterator(); while (it.hasNext()) { final Column originalColumn = (Column) it.next(); // final Column newColumn = new // Column(originalColumn.getName()); mto.addColumn(originalColumn); } mto.createForeignKey(); // now determine if a join should be created if (collectionTable.getName().equalsIgnoreCase(elementPC.getTable().getName())) { elementPC.addProperty(inverseRefProperty); } else { // create a join final Join join = new Join(); join.setPersistentClass(elementPC); join.setTable(collectionTable); join.addProperty(inverseRefProperty); final ManyToOne keyValue = new ManyToOne(getMappings(), collectionTable); join.setKey(keyValue); @SuppressWarnings("unchecked") final Iterator<Column> keyColumns = collection.getElement().getColumnIterator(); while (keyColumns.hasNext()) { keyValue.addColumn(keyColumns.next()); } keyValue.setReferencedEntityName(elementPC.getEntityName()); keyValue.setTable(collectionTable); keyValue.createForeignKey(); elementPC.addJoin(join); } } // add an opposite index if (collection.isIndexed() && !collection.isMap()) { Table collectionTable = collection.getCollectionTable(); IndexedCollection indexedCollection = (IndexedCollection) collection; final Column column = (Column) indexedCollection.getIndex().getColumnIterator().next(); final Property indexProperty = new Property(); indexProperty.setName(StoreUtil.getExtraLazyInverseIndexPropertyName(ef)); final Map<Object, Object> metas = new HashMap<Object, Object>(); final MetaAttribute metaAttribute = new MetaAttribute( HbConstants.SYNTHETIC_PROPERTY_INDICATOR); metaAttribute.addValue("true"); metas.put(HbConstants.SYNTHETIC_PROPERTY_INDICATOR, metaAttribute); indexProperty.setMetaAttributes(metas); indexProperty.setNodeName(indexProperty.getName()); indexProperty.setPropertyAccessorName(SyntheticPropertyHandler.class.getName()); // always make this nullable, nullability is controlled // by the main property indexProperty.setOptional(true); Join join = null; @SuppressWarnings("unchecked") final Iterator<Join> it = (Iterator<Join>) elementPC.getJoinIterator(); while (it.hasNext()) { final Join foundJoin = it.next(); if (foundJoin.getTable().getName().equalsIgnoreCase(collectionTable.getName())) { join = foundJoin; collectionTable = join.getTable(); break; } } final SimpleValue sv = new SimpleValue(getMappings(), indexedCollection.getIndex().getTable()); sv.setTypeName("integer"); // final Column svColumn = new Column(column.getName()); sv.addColumn(column); // checkColumnExists(collectionTable, // svColumn)); indexProperty.setValue(sv); if (join != null) { join.addProperty(indexProperty); } else { elementPC.addProperty(indexProperty); } } } } } }