org.eclipse.persistence.internal.helper.DatabaseField Java Examples

The following examples show how to use org.eclipse.persistence.internal.helper.DatabaseField. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JPAMTableDefinition.java    From jeddict with Apache License 2.0 6 votes vote down vote up
/**
 * Build a foreign key constraint using
 * FieldDefinition.getForeignKeyFieldName().
 */
@Override
protected ForeignKeyConstraint buildForeignKeyConstraint(FieldDefinition field, DatabasePlatform platform) {
    Vector sourceFields = new Vector();
    Vector targetFields = new Vector();
    ForeignKeyConstraint fkConstraint = new ForeignKeyConstraint();
    DatabaseField tempTargetField = new DatabaseField(field.getForeignKeyFieldName());
    DatabaseField tempSourceField = new DatabaseField(field.getName());

    sourceFields.add(tempSourceField.getName());
    targetFields.add(tempTargetField.getName());

    fkConstraint.setSourceFields(sourceFields);
    fkConstraint.setTargetFields(targetFields);
    fkConstraint.setTargetTable(tempTargetField.getTable().getQualifiedNameDelimited(platform));
    String tempName = buildForeignKeyConstraintName(this.getName(), tempSourceField.getName(), platform.getMaxForeignKeyNameSize(), platform);

    fkConstraint.setName(tempName);
    return fkConstraint;
}
 
Example #2
Source File: UuidMappingProcessor.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void process(MappingProcessorContext context) {
    DatabaseMapping mapping = context.getMapping();
    Session session = context.getSession();

    MetaClass metaClass = metadata.getSession().getClassNN(mapping.getDescriptor().getJavaClass());

    String attributeName = mapping.getAttributeName();
    MetaProperty metaProperty = metaClass.getPropertyNN(attributeName);
    if (metaProperty.getRange().isDatatype()) {
        if (metaProperty.getJavaType().equals(UUID.class)) {
            ((DirectToFieldMapping) mapping).setConverter(UuidConverter.getInstance());
            setDatabaseFieldParameters(session, mapping.getField());
        }
    } else if (metaProperty.getRange().isClass() && !metaProperty.getRange().getCardinality().isMany()) {
        MetaClass refMetaClass = metaProperty.getRange().asClass();
        MetaProperty refPkProperty = metadata.getTools().getPrimaryKeyProperty(refMetaClass);
        if (refPkProperty != null && refPkProperty.getJavaType().equals(UUID.class)) {
            for (DatabaseField field : ((OneToOneMapping) mapping).getForeignKeyFields()) {
                setDatabaseFieldParameters(session, field);
            }
        }
    }

}
 
Example #3
Source File: UuidMappingProcessor.java    From cuba with Apache License 2.0 6 votes vote down vote up
private void setDatabaseFieldParameters(Session session, DatabaseField field) {
    if (session.getPlatform() instanceof PostgreSQLPlatform) {
        field.setSqlType(Types.OTHER);
        field.setType(UUID.class);
        field.setColumnDefinition("UUID");
    } else if (session.getPlatform() instanceof MySQLPlatform) {
        field.setSqlType(Types.VARCHAR);
        field.setType(String.class);
        field.setColumnDefinition("varchar(32)");
    } else if (session.getPlatform() instanceof HSQLPlatform) {
        field.setSqlType(Types.VARCHAR);
        field.setType(String.class);
        field.setColumnDefinition("varchar(36)");
    } else if (session.getPlatform() instanceof SQLServerPlatform) {
        field.setSqlType(Types.VARCHAR);
        field.setType(String.class);
        field.setColumnDefinition("uniqueidentifier");
    } else if (session.getPlatform() instanceof OraclePlatform) {
        field.setSqlType(Types.VARCHAR);
        field.setType(String.class);
        field.setColumnDefinition("varchar2(32)");
    } else {
        field.setSqlType(Types.VARCHAR);
        field.setType(String.class);
    }
}
 
Example #4
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
protected void processAdditionalTablePkFields(LinkedList<Entity> intrinsicEntity, DBRelationalDescriptor descriptor) {
        // only if there are additional tables
        if (!descriptor.hasMultipleTables()) {
            return;
        }
//descriptor.getMappings().get(0).getField()
        DatabaseTable databaseTable = null;
        Iterator dbTblIter = descriptor.getTables().iterator();
        while (dbTblIter.hasNext()) {
            databaseTable = (DatabaseTable) dbTblIter.next();
            Map<DatabaseField, DatabaseField> srcFields = descriptor.getAdditionalTablePrimaryKeyFields().get(databaseTable);
            if ((null != srcFields) && srcFields.size() > 0) {
                // srcFields is from the secondary field to the primary key field
                // Let's make fk constraint from the secondary field to the primary key field
                List<DatabaseField> fkFields = new ArrayList<>();
                List<DatabaseField> pkFields = new ArrayList<>();

                for (DatabaseField pkField : srcFields.keySet()) {
                    pkFields.add(pkField);
                    fkFields.add(srcFields.get(pkField));
                }
                //TODO : use isInherited instead of true value
                addJoinColumnsFkConstraint(null, null, intrinsicEntity, null, false, descriptor, fkFields, pkFields, descriptor.isCascadeOnDeleteSetOnDatabaseOnSecondaryTables());
            }
        }
    }
 
Example #5
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private Attribute getManagedAttribute(ClassDescriptor refDescriptor, DatabaseField dbField, LinkedList<Attribute> intrinsicAttribute) {
    if (refDescriptor != null) {
        for (DatabaseMapping refMapping : refDescriptor.getMappings()) {
            if(!refMapping.getFields()
                    .stream()
                    .filter(field -> field == dbField)
                    .findAny()
                    .isPresent()){
                continue;
            }
            
            if (refMapping.getFields().size() > 1) {
                intrinsicAttribute.add((Attribute) refMapping.getProperty(Attribute.class));
                if(refMapping.getReferenceDescriptor() == refDescriptor){ //self-relationship with composite pk
                    return (Attribute) refMapping.getProperty(Attribute.class);
                } else {
                    return getManagedAttribute(refMapping.getReferenceDescriptor(), dbField, intrinsicAttribute);
                }
            } else if (!refMapping.getFields().isEmpty() && refMapping.getFields().get(0) == dbField) {
                intrinsicAttribute.add((Attribute) refMapping.getProperty(Attribute.class));
                return (Attribute) refMapping.getProperty(Attribute.class);
            }
        }
    }
    return null;
}
 
Example #6
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
/**
 * The ContainerPolicy may contain some additional fields that should be
 * added to the table
 *
 * @see MappedKeyMapContainerPolicy
 */
protected void addFieldsForMappedKeyMapContainerPolicy(ManagedClass managedClass, Attribute managedAttribute, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, boolean isInherited, ContainerPolicy cp, TableDefinition table) {
    if (cp.isMappedKeyMapPolicy()) {
        List<DatabaseField> keyFields = cp.getIdentityFieldsForMapKey();
        Iterator<DatabaseField> i = keyFields.iterator();
        while (i.hasNext()) {
            DatabaseField foreignKey = i.next();
            // to fetch managed embedded attribute
            LinkedList<Attribute> intrinsicAttribute_Local = new LinkedList<>(intrinsicAttribute);
            Attribute managedAttribute_Local = managedAttribute;
            if (managedAttribute instanceof MapKeyHandler && ((MapKeyHandler) managedAttribute).getMapKeyEmbeddable() != null) {
                managedAttribute_Local = getManagedAttribute(cp.getDescriptorForMapKey(), foreignKey, intrinsicAttribute_Local);
            }
            FieldDefinition fieldDef = getFieldDefFromDBField(intrinsicEntity.get(0), intrinsicAttribute_Local, managedAttribute_Local, false, false, false, isInherited, false, false, true, foreignKey);
            if (!table.getFields().contains(fieldDef)) {
                table.addField(fieldDef);
            }
        }
        Map<DatabaseField, DatabaseField> foreignKeys = ((MappedKeyMapContainerPolicy) cp).getForeignKeyFieldsForMapKey();
        if (foreignKeys != null) {
            addForeignMappingFkConstraint(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, foreignKeys, false);
        }
    }
}
 
Example #7
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private DatabaseMapping getDatabaseMapping(ClassDescriptor descriptor, DatabaseField databaseField) {
    DatabaseMapping databaseMapping = mappings.get(databaseField);
    if (databaseMapping == null) {
        for (DatabaseMapping m : descriptor.getMappings()) {
            for (DatabaseField f : m.getFields()) {
                if (mappings.get(f) == null) {
                    mappings.put(f, m);
                }
                if (databaseField == f) {
                    databaseMapping = m;
                }
            }
        }
    }
    return databaseMapping;
}
 
Example #8
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
/**
 * Build a field definition object from a database field.
 */
protected FieldDefinition getFieldDefFromDBField(Entity intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, Attribute managedAttribute, boolean inverse, boolean foriegnKey, boolean relationTable, boolean inherited, boolean dtype, boolean primaryKeyJoinColumn, boolean mapKey, DatabaseField dbField) {
    Supplier<JPAMFieldDefinition> fieldDefSupplier = () -> {
        JPAMFieldDefinition fieldDef;
        if (inherited) {
            fieldDef = new JPAMFieldDefinition(intrinsicEntity, managedAttribute, inverse, foriegnKey, relationTable);
        } else if (dtype) {
            fieldDef = new JPAMFieldDefinition(intrinsicEntity);
        } else if (primaryKeyJoinColumn) {
            fieldDef = new JPAMFieldDefinition(intrinsicEntity, primaryKeyJoinColumn);
        } else if (mapKey) {
            fieldDef = new JPAMFieldDefinition(intrinsicAttribute, managedAttribute, mapKey);
        } else {
            fieldDef = new JPAMFieldDefinition(intrinsicAttribute, managedAttribute, inverse, foriegnKey, relationTable);
        }
        return fieldDef;
    };

    return getFieldDefFromDBField(fieldDefSupplier, dbField);
}
 
Example #9
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
protected void addForeignMappingFkConstraint(ManagedClass managedClass, Attribute managedAttribute, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, boolean isInherited, final Map<DatabaseField, DatabaseField> srcFields, boolean cascadeOnDelete) {
    // srcFields map from the foreign key field to the target key field

    if (srcFields.isEmpty()) {
        return;
    }

    List<DatabaseField> fkFields = new ArrayList<>();
    List<DatabaseField> targetFields = new ArrayList<>();

    for (DatabaseField fkField : srcFields.keySet()) {
        fkFields.add(fkField);
        targetFields.add(srcFields.get(fkField));
    }
    addJoinColumnsFkConstraint(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, null, fkFields, targetFields, cascadeOnDelete);
}
 
Example #10
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 5 votes vote down vote up
protected void addForeignKeyFieldToSourceTargetTable(ManagedClass managedClass, Attribute managedAttribute, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, boolean isInherited, OneToOneMapping mapping) {
    if (!mapping.isForeignKeyRelationship()
            || (mapping.getReferenceDescriptor().hasTablePerClassPolicy()
            && mapping.getReferenceDescriptor().getTablePerClassPolicy().hasChild())) {
        return;
    }
    boolean cascadeDelete = false;
    // Find mappedBy target mapping to check constraint cascade.
    for (DatabaseField foreignKey : mapping.getSourceToTargetKeyFields().values()) {
        DatabaseMapping mappedBy = mapping.getReferenceDescriptor().getObjectBuilder().getMappingForField(foreignKey);
        if (mappedBy != null && mappedBy.isOneToOneMapping()) {
            cascadeDelete = ((OneToOneMapping) mappedBy).isCascadeOnDeleteSetOnDatabase();
        } else {
            List<DatabaseMapping> readOnlyMappings = mapping.getReferenceDescriptor().getObjectBuilder().getReadOnlyMappingsForField(foreignKey);
            if (readOnlyMappings != null) {
                for (DatabaseMapping mappedByPK : readOnlyMappings) {
                    if (mappedByPK.isOneToOneMapping()) {
                        cascadeDelete = ((OneToOneMapping) mappedByPK).isCascadeOnDeleteSetOnDatabase();
                        if (cascadeDelete) {
                            break;
                        }
                    }
                }
            }
        }
        if (cascadeDelete) {
            break;
        }
    }

    // If the mapping is optional and uses primary key join columns, don't
    // generate foreign key constraints which would require the target to
    // always be set.
    if (!mapping.isOptional() || !mapping.isOneToOnePrimaryKeyRelationship()) {
        addForeignMappingFkConstraint(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, mapping.getSourceToTargetKeyFields(), cascadeDelete);
    }
}
 
Example #11
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 5 votes vote down vote up
/**
 * Build and add a field definition object to relation table
 */
protected void setFieldToRelationTable(Entity intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, Attribute managedAttribute, boolean inverse, boolean isInherited, DatabaseField dbField, TableDefinition table) {
    FieldDefinition fieldDef = getFieldDefFromDBField(intrinsicEntity, intrinsicAttribute, managedAttribute, inverse, true, true, isInherited, false, false, false, dbField);

    if (!table.getFields().contains(fieldDef)) {
        //only add the field once, to avoid add twice if m:m is bi-directional.
        table.addField(getFieldDefFromDBField(dbField));
        fieldDef.setIsPrimaryKey(true); // make this a PK as we will be creating constrains later
    }
}
 
Example #12
Source File: StudioEclipseLinkSessionEventListener.java    From cuba with Apache License 2.0 5 votes vote down vote up
private void setDatabaseFieldParameters(Session session, DatabaseField field) {
    if (session.getPlatform() instanceof PostgreSQLPlatform) {
        field.setSqlType(Types.OTHER);
        field.setType(UUID.class);
    } else {
        field.setSqlType(Types.VARCHAR);
        field.setType(String.class);
    }
    field.setColumnDefinition("UUID");
}
 
Example #13
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 5 votes vote down vote up
/**
 * Build field definitions and foreign key constraints for all many-to-many
 * relation table.
 */
protected void buildRelationTableFields(ManagedClass managedClass, Attribute managedAttribute, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, boolean inverse, boolean isInherited, ForeignReferenceMapping mapping, TableDefinition table, List<DatabaseField> fkFields, List<DatabaseField> targetFields) {
    assert fkFields.size() > 0 && fkFields.size() == targetFields.size();

    DatabaseField fkField;
    DatabaseField targetField = null;
    List<String> fkFieldNames = new ArrayList();
    List<String> targetFieldNames = new ArrayList();

    for (int index = 0; index < fkFields.size(); index++) {
        fkField = fkFields.get(index);
        targetField = targetFields.get(index);
        fkFieldNames.add(fkField.getNameDelimited(databasePlatform));
        targetFieldNames.add(targetField.getNameDelimited(databasePlatform));

        fkField = resolveDatabaseField(fkField, targetField);
        setFieldToRelationTable(intrinsicEntity.get(0), intrinsicAttribute, managedAttribute, inverse, isInherited, fkField, table);
    }

    // add a foreign key constraint from fk field to target field
    DatabaseTable targetTable = targetField.getTable();
    TableDefinition targetTblDef = getTableDefFromDBTable(managedClass, managedAttribute, intrinsicEntity, targetTable);

    if (mapping.getDescriptor().hasTablePerClassPolicy()) {
        return;
    }
    if (mapping.getReferenceDescriptor().hasTablePerClassPolicy()
            && mapping.getReferenceDescriptor().getTablePerClassPolicy().hasChild()) {
        return;
    }
    addForeignKeyConstraint(table, targetTblDef, fkFieldNames, targetFieldNames, mapping.isCascadeOnDeleteSetOnDatabase());
}
 
Example #14
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 5 votes vote down vote up
/**
     * Build relation table definitions for all many-to-many relationships in a
     * EclipseLink descriptor.
     */
    protected void buildRelationTableDefinition(ManagedClass managedClass, Attribute managedAttribute, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, boolean isInherited, ForeignReferenceMapping mapping, RelationTableMechanism relationTableMechanism, DatabaseField listOrderField, ContainerPolicy cp) {
        //first create relation table
        TableDefinition table = getTableDefFromDBTable(managedClass, managedAttribute, intrinsicEntity, relationTableMechanism.getRelationTable());

        //add source foreign key fields into the relation table
        List<DatabaseField> srcFkFields = relationTableMechanism.getSourceRelationKeyFields();//Relation Table
        List<DatabaseField> srcKeyFields = relationTableMechanism.getSourceKeyFields();//Entity(Owner) Table

        buildRelationTableFields(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, false, isInherited, mapping, table, srcFkFields, srcKeyFields);

        //add target foreign key fields into the relation table
        List<DatabaseField> targFkFields = relationTableMechanism.getTargetRelationKeyFields();//Relation Table
        List<DatabaseField> targKeyFields = relationTableMechanism.getTargetKeyFields();//Entity(MappedBy) Table

//        attribute.getConnectedAttribute()
        buildRelationTableFields(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, true, isInherited, mapping, table, targFkFields, targKeyFields);

        if (cp != null) {
            addFieldsForMappedKeyMapContainerPolicy(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, cp, table);
        }

        if (listOrderField != null) {
            FieldDefinition fieldDef = getFieldDefFromDBField(listOrderField);
            if (!table.getFields().contains(fieldDef)) {
                table.addField(fieldDef);
            }
        }
    }
 
Example #15
Source File: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testExtensionAttribute_eclipselink_data() {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	ClassDescriptor referenceDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObjectExtension.class);
	assertNotNull("A classDescriptor should have been retrieved from JPA for TestDataObject", classDescriptor);
	assertNotNull("A classDescriptor should have been retrieved from JPA for TestDataObjectExtension",
               referenceDescriptor);
	DatabaseMapping databaseMapping = classDescriptor.getMappingForAttributeName("extension");
       assertNotNull("extension mapping missing from metamodel", databaseMapping);
       assertTrue("Should be a OneToOne mapping", databaseMapping instanceof OneToOneMapping);
       OneToOneMapping mapping = (OneToOneMapping)databaseMapping;

       assertEquals("Should be mapped by primaryKeyProperty", "primaryKeyProperty", mapping.getMappedBy());
       Map<DatabaseField, DatabaseField> databaseFields = mapping.getSourceToTargetKeyFields();
       assertEquals(1, databaseFields.size());
       for (DatabaseField sourceField : databaseFields.keySet()) {
           DatabaseField targetField = databaseFields.get(sourceField);
           assertEquals("PK_PROP", sourceField.getName());
           assertEquals("PK_PROP", targetField.getName());
       }

	assertNotNull("Reference descriptor missing from relationship", mapping.getReferenceDescriptor());
	assertEquals("Reference descriptor should be the one for TestDataObjectExtension", referenceDescriptor,
               mapping.getReferenceDescriptor());

	assertNotNull("selection query relationship missing", mapping.getSelectionQuery());
	assertNotNull("selection query missing name", mapping.getSelectionQuery().getName());
	assertEquals("selection query name incorrect", "extension", mapping.getSelectionQuery().getName());
	assertNotNull("selection query reference class", mapping.getSelectionQuery().getReferenceClass());
	assertEquals("selection query reference class incorrect", TestDataObjectExtension.class,
               mapping.getSelectionQuery().getReferenceClass());
	assertNotNull("selection query reference class name", mapping.getSelectionQuery().getReferenceClassName());
	assertNotNull("selection query source mapping missing", mapping.getSelectionQuery().getSourceMapping());
	assertEquals("selection query source mapping incorrect", mapping,
               mapping.getSelectionQuery().getSourceMapping());
}
 
Example #16
Source File: CamelNamingStrategy.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
private void camelCaseToUnderscore(Vector<DatabaseMapping> mappings) {
    for (DatabaseMapping mapping : mappings) {
        DatabaseField field = mapping.getField();
        if (mapping.isDirectToFieldMapping() && !mapping.isPrimaryKeyMapping()) {
            String attributeName = mapping.getAttributeName();
            String underScoredFieldName = camelCaseToUnderscore(attributeName);
            field.setName(underScoredFieldName);
        }
    }
}
 
Example #17
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
public DataObjectRelationship addExtensionRelationship(Class<?> entityClass, String extensionPropertyName,
		Class<?> extensionEntityClass) {
	ClassDescriptor entityDescriptor = getClassDescriptor(entityClass);
	ClassDescriptor extensionEntityDescriptor = getClassDescriptor(extensionEntityClass);

	if (LOG.isDebugEnabled()) {
		LOG.debug("About to attempt to inject a 1:1 relationship on PKs between " + entityDescriptor + " and "
				+ extensionEntityDescriptor);
	}
	OneToOneMapping dm = (OneToOneMapping) entityDescriptor.newOneToOneMapping();
	dm.setAttributeName(extensionPropertyName);
	dm.setReferenceClass(extensionEntityClass);
	dm.setDescriptor(entityDescriptor);
	dm.setIsPrivateOwned(true);
	dm.setJoinFetch(ForeignReferenceMapping.OUTER_JOIN);
	dm.setCascadeAll(true);
	dm.setIsLazy(false);
	dm.dontUseIndirection();
	dm.setIsOneToOneRelationship(true);
	dm.setRequiresTransientWeavedFields(false);

       OneToOneMapping inverse = findExtensionInverse(extensionEntityDescriptor, entityClass);
       dm.setMappedBy(inverse.getAttributeName());
       for (DatabaseField sourceField : inverse.getSourceToTargetKeyFields().keySet()) {
           DatabaseField targetField = inverse.getSourceToTargetKeyFields().get(sourceField);
           // reverse them, pass the source from the inverse as our target and the target from the inverse as our source
           dm.addTargetForeignKeyField(sourceField, targetField);
       }

       dm.preInitialize(getEclipseLinkEntityManager().getDatabaseSession());
	dm.initialize(getEclipseLinkEntityManager().getDatabaseSession());
	entityDescriptor.addMapping(dm);
	entityDescriptor.getObjectBuilder().initialize(getEclipseLinkEntityManager().getDatabaseSession());

       // build the data object relationship
       ManagedTypeImpl<?> managedType = (ManagedTypeImpl<?>)getEntityManager().getMetamodel().managedType(entityClass);
       SingularAttributeImpl<?, ?> singularAttribute = new SingularAttributeLocal(managedType, dm);
       return getRelationshipMetadata(singularAttribute);
}
 
Example #18
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 4 votes vote down vote up
protected FieldDefinition getFieldDefFromDBField(DatabaseField dbField) {
    return getFieldDefFromDBField(null, null, null, false, false, false, false, false, false, false, dbField);
}
 
Example #19
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
protected void populateImplementationSpecificRelationshipLevelMetadata(DataObjectRelationshipImpl relationship,
		SingularAttribute<?, ?> rd) {
	// We need to go into the repository and grab the table name.
	Class<?> referencedClass = rd.getBindableJavaType();
	EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass);
	if (referencedEntityType instanceof EntityTypeImpl) {
		relationship
				.setBackingObjectName(((EntityTypeImpl<?>) referencedEntityType).getDescriptor().getTableName());
	}
	// Set to read only if store (save) operations should not be pushed through
	PersistentAttributeType persistentAttributeType = rd.getPersistentAttributeType();

	if (rd instanceof SingularAttributeImpl) {
		SingularAttributeImpl<?, ?> rel = (SingularAttributeImpl<?, ?>) rd;

		OneToOneMapping relationshipMapping = (OneToOneMapping) rel.getMapping();
		relationship.setReadOnly(relationshipMapping.isReadOnly());
		relationship.setSavedWithParent(relationshipMapping.isCascadePersist());
		relationship.setDeletedWithParent(relationshipMapping.isCascadeRemove());
		relationship.setLoadedAtParentLoadTime(relationshipMapping.isCascadeRefresh()
				&& !relationshipMapping.isLazy());
		relationship.setLoadedDynamicallyUponUse(relationshipMapping.isCascadeRefresh()
				&& relationshipMapping.isLazy());

           List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>();
           List<String> referencedEntityPkFields = getPrimaryKeyAttributeNames(referencedEntityType);

           for (String referencedEntityPkField : referencedEntityPkFields) {
               for (Map.Entry<DatabaseField, DatabaseField> entry :
                       relationshipMapping.getTargetToSourceKeyFields().entrySet()) {
                   DatabaseField childDatabaseField = entry.getKey();
                   String childFieldName = getPropertyNameFromDatabaseColumnName(referencedEntityType,
                           childDatabaseField.getName());

                   if (referencedEntityPkField.equalsIgnoreCase(childFieldName)) {
                       DatabaseField parentDatabaseField = entry.getValue();
                       String parentFieldName = getPropertyNameFromDatabaseColumnName(rd.getDeclaringType(),
                               parentDatabaseField.getName());

                       if (parentFieldName != null) {
                           attributeRelationships
                                   .add(new DataObjectAttributeRelationshipImpl(parentFieldName, childFieldName));
                           break;
                       } else {
                           LOG.warn("Unable to find parent field reference.  There may be a JPA mapping problem on " +
                                   referencedEntityType.getJavaType() + ": " + relationship);
                       }
                   }
               }
           }

           relationship.setAttributeRelationships(attributeRelationships);

           populateInverseRelationship(relationshipMapping, relationship);

	} else {
		// get what we can based on JPA values (note that we just set some to have values here)
		relationship.setReadOnly(persistentAttributeType == PersistentAttributeType.MANY_TO_ONE);
		relationship.setSavedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
		relationship.setDeletedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
		relationship.setLoadedAtParentLoadTime(true);
		relationship.setLoadedDynamicallyUponUse(false);
	}
}
 
Example #20
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 4 votes vote down vote up
protected void addJoinColumnsFkConstraint(ManagedClass managedClass, Attribute managedAttribute, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, boolean isInherited, DBRelationalDescriptor descriptor, List<DatabaseField> fkFields, List<DatabaseField> targetFields, boolean cascadeOnDelete) {
    assert fkFields.size() == targetFields.size();

    if (fkFields.isEmpty()) {
        return;
    }

    DatabaseField fkField;
    DatabaseField targetField = null;
    List<String> fkFieldNames = new ArrayList();
    List<String> targetFieldNames = new ArrayList();

    DatabaseTable sourceTable = fkFields.get(0).getTable();
    TableDefinition sourceTableDef = getTableDefFromDBTable(sourceTable);

    for (int i = 0; i < fkFields.size(); i++) {
        fkField = fkFields.get(i);
        targetField = targetFields.get(i);

        if (descriptor != null && managedClass == null && managedAttribute == null) {
            DatabaseMapping databaseMapping = getDatabaseMapping(descriptor, targetField);
            if (databaseMapping != null) {
                managedAttribute = (Attribute) databaseMapping.getProperty(Attribute.class);
                intrinsicAttribute = new LinkedList<>();
                intrinsicAttribute.add(managedAttribute);
                managedClass = ((EntitySpecAccessor) descriptor.getAccessor()).getEntity();
                intrinsicEntity = new LinkedList<>();
                if(managedAttribute.getJavaClass() instanceof Entity){ //Todo MappedSuperClass ?
                    intrinsicEntity.add((Entity) managedAttribute.getJavaClass());
                }
            } else {
                 DBValidationException exception = new DBValidationException(targetField.getName() + " column not found");
                 exception.setJavaClass(intrinsicEntity.get(0));
                 throw exception;
            }
        }

        fkFieldNames.add(fkField.getNameDelimited(this.databasePlatform));
        targetFieldNames.add(targetField.getNameDelimited(this.databasePlatform));

        FieldDefinition fkFieldDef = fieldMap.get(fkField);
        FieldDefinition targetFieldDef = fieldMap.get(targetField);

        if (targetFieldDef != null) {
            // UnidirectionalOneToOneMapping case
            if (fkFieldDef == null) {
                boolean primaryKeyJoinColumn = intrinsicAttribute.size() == 1 && intrinsicAttribute.peek() instanceof Id;
                fkFieldDef = getFieldDefFromDBField(intrinsicEntity.get(0), intrinsicAttribute, managedAttribute, true, true, false, isInherited, false, primaryKeyJoinColumn, false, fkField);//TODO confirm boolean
                if (!sourceTableDef.getFields().contains(fkFieldDef)) {
                    sourceTableDef.addField(fkFieldDef);
                }
            }//

            // Set the fkFieldDef type definition to the that of the target if one is not set.
            if (fkFieldDef.getTypeDefinition() == null || fkFieldDef.getTypeDefinition().trim().equals("")) {
                fkFieldDef.setTypeDefinition(targetFieldDef.getTypeDefinition());
            }

            // Also ensure that the type, size and subsize of the foreign key field is
            // same as that of the original field.
            fkFieldDef.setType(targetFieldDef.getType());
            fkFieldDef.setSize(targetFieldDef.getSize());
            fkFieldDef.setSubSize(targetFieldDef.getSubSize());
        }
    }

    // add a foreign key constraint
    DatabaseTable targetTable = targetField.getTable();
    TableDefinition targetTableDef = getTableDefFromDBTable(targetTable);

    addForeignKeyConstraint(sourceTableDef, targetTableDef, fkFieldNames, targetFieldNames, cascadeOnDelete);
}
 
Example #21
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 4 votes vote down vote up
protected FieldDefinition getFieldDefFromDBField(Supplier<JPAMFieldDefinition> fieldDefSupplier, DatabaseField dbField) {
    FieldDefinition fieldDef = this.fieldMap.get(dbField);
    if (fieldDef == null) {
        fieldDef = fieldDefSupplier.get();
        fieldDef.setName(dbField.getNameDelimited(databasePlatform));

        //added for extending tables where the field needs to be looked up
        fieldDef.setDatabaseField(dbField);

        if (dbField.getColumnDefinition() != null && dbField.getColumnDefinition().length() > 0) {
            // This column definition would include the complete definition of the
            // column like type, size,  "NULL/NOT NULL" clause, unique key clause
            fieldDef.setTypeDefinition(dbField.getColumnDefinition());
        } else {
            Class fieldType = dbField.getType();
            FieldTypeDefinition fieldTypeDef = (fieldType == null) ? null : databasePlatform.getFieldTypeDefinition(fieldType);

            // Check if the user field is a String and only then allow the length specified
            // in the @Column annotation to be set on the field.
            if (fieldType != null) {
                // If a length has been specified, set it, otherwise let the
                // field def from individual platforms handle it.
                if (dbField.getLength() > 0) {
                    fieldDef.setSize(dbField.getLength());
                } else if (dbField.getPrecision() > 0) {
                    fieldDef.setSize(dbField.getPrecision());
                    fieldDef.setSubSize(dbField.getScale());
                }
            }

            if ((fieldType == null) || (!fieldType.isPrimitive() && (fieldTypeDef == null))) {
                //TODO: log a warning for inaccessible type or not convertable type.
                AbstractSessionLog.getLog().log(SessionLog.CONFIG, SessionLog.METADATA, "field_type_set_to_java_lang_string", dbField.getQualifiedName(), fieldType);

                //set the default type (lang.String) to all un-resolved java type, like null, Number, util.Date, NChar/NType, Calendar
                //sql.Blob/Clob, Object, or unknown type). Please refer to bug 4352820.
                fieldDef.setType(ClassConstants.STRING);
            } else {
                //need to convert the primitive type if applied.
                fieldDef.setType(ConversionManager.getObjectClass(fieldType));
            }

            fieldDef.setShouldAllowNull(dbField.isNullable());
            fieldDef.setUnique(dbField.isUnique());
        }
        this.fieldMap.put(dbField, fieldDef);
        this.databaseFields.put(dbField, dbField);
    }

    return fieldDef;
}
 
Example #22
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 4 votes vote down vote up
/**
 * Resolve the foreign key database field metadata in relation table or
 * direct collection/map table. Those metadata includes type, and maybe
 * dbtype/size/subsize if DatabaseField carries those info.
 */
protected DatabaseField resolveDatabaseField(DatabaseField childField, DatabaseField parentField) {
    //set through the type from the source table key field to the relation or direct collection table key field.
    DatabaseField resolvedDatabaseField = new DatabaseField();
    // find original field in the parent table, which contains actual type definitions
    // if 'resolvedParentField' is null, there is no corresponding field definition (typo?)
    DatabaseField resolvedParentField = databaseFields.get(parentField);

    resolvedDatabaseField.setName(childField.getName());
    //Table should be set, otherwise other same name field will be used wrongly because equals() is true.
    //Fix for GF#1392 the same name column for the entity and many-to-many table cause wrong pk constraint.
    resolvedDatabaseField.setTable(childField.getTable());

    // type definitions from parent field definition
    if (resolvedParentField != null) {
        resolvedDatabaseField.setType(resolvedParentField.getType());
        resolvedDatabaseField.setScale(resolvedParentField.getScale());
        resolvedDatabaseField.setLength(resolvedParentField.getLength());
        resolvedDatabaseField.setPrecision(resolvedParentField.getPrecision());
    }

    // these are defined in childField definition(see @JoinColumn)
    resolvedDatabaseField.setUnique(childField.isUnique());
    resolvedDatabaseField.setNullable(childField.isNullable());
    resolvedDatabaseField.setUpdatable(childField.isUpdatable());
    resolvedDatabaseField.setInsertable(childField.isInsertable());
    resolvedDatabaseField.setUseDelimiters(childField.shouldUseDelimiters());
    resolvedDatabaseField.useUpperCaseForComparisons(childField.getUseUpperCaseForComparisons());
    resolvedDatabaseField.setNameForComparisons(childField.getNameForComparisons());

    String columnDef = childField.getColumnDefinition();
    if (columnDef == null || columnDef.trim().equals("")) {
        // if childField has no column definition, follow the definition of the parent field
        if (resolvedParentField != null) {
            resolvedDatabaseField.setColumnDefinition(resolvedParentField.getColumnDefinition());
        }
    } else {
        resolvedDatabaseField.setColumnDefinition(columnDef);
    }

    return resolvedDatabaseField;
}
 
Example #23
Source File: PersistenceTools.java    From cuba with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an ID of directly referenced entity without loading it from DB.
 * <p>
 * If the view does not contain the reference and {@link View#loadPartialEntities()} is true,
 * the returned {@link RefId} will have {@link RefId#isLoaded()} = false.
 *
 * <p>Usage example:
 * <pre>
 *   PersistenceTools.RefId refId = persistenceTools.getReferenceId(doc, "currency");
 *   if (refId.isLoaded()) {
 *       String currencyCode = (String) refId.getValue();
 *   }
 * </pre>
 *
 * @param entity   entity instance in managed state
 * @param property name of reference property
 * @return {@link RefId} instance which contains the referenced entity ID
 * @throws IllegalArgumentException if the specified property is not a reference
 * @throws IllegalStateException    if the entity is not in Managed state
 * @throws RuntimeException         if anything goes wrong when retrieving the ID
 */
public RefId getReferenceId(BaseGenericIdEntity entity, String property) {
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    MetaProperty metaProperty = metaClass.getPropertyNN(property);

    if (!metaProperty.getRange().isClass() || metaProperty.getRange().getCardinality().isMany())
        throw new IllegalArgumentException("Property is not a reference");

    if (!entityStates.isManaged(entity))
        throw new IllegalStateException("Entity must be in managed state");

    String[] inaccessibleAttributes = BaseEntityInternalAccess.getInaccessibleAttributes(entity);
    if (inaccessibleAttributes != null) {
        for (String inaccessibleAttr : inaccessibleAttributes) {
            if (inaccessibleAttr.equals(property))
                return RefId.createNotLoaded(property);
        }
    }

    if (entity instanceof FetchGroupTracker) {
        FetchGroup fetchGroup = ((FetchGroupTracker) entity)._persistence_getFetchGroup();
        if (fetchGroup != null) {
            if (!fetchGroup.containsAttributeInternal(property))
                return RefId.createNotLoaded(property);
            else {
                Entity refEntity = (Entity) entity.getValue(property);
                return RefId.create(property, refEntity == null ? null : refEntity.getId());
            }
        }
    }

    try {
        Class<?> declaringClass = metaProperty.getDeclaringClass();
        if (declaringClass == null) {
            throw new RuntimeException("Property does not belong to persistent class");
        }

        Method vhMethod = declaringClass.getDeclaredMethod(String.format("_persistence_get_%s_vh", property));
        vhMethod.setAccessible(true);

        ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity);
        if (vh instanceof DatabaseValueHolder) {
            AbstractRecord row = ((DatabaseValueHolder) vh).getRow();
            if (row != null) {
                Session session = persistence.getEntityManager().getDelegate().unwrap(Session.class);
                ClassDescriptor descriptor = session.getDescriptor(entity);
                DatabaseMapping mapping = descriptor.getMappingForAttributeName(property);
                Vector<DatabaseField> fields = mapping.getFields();
                if (fields.size() != 1) {
                    throw new IllegalStateException("Invalid number of columns in mapping: " + fields);
                }
                Object value = row.get(fields.get(0));
                if (value != null) {
                    ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                    DatabaseMapping refMapping = refDescriptor.getMappingForAttributeName(metadata.getTools().getPrimaryKeyName(metaClass));
                    if (refMapping instanceof AbstractColumnMapping) {
                        Converter converter = ((AbstractColumnMapping) refMapping).getConverter();
                        if (converter != null) {
                            return RefId.create(property, converter.convertDataValueToObjectValue(value, session));
                        }
                    }
                }
                return RefId.create(property, value);
            } else {
                return RefId.create(property, null);
            }
        }
        return RefId.createNotLoaded(property);
    } catch (Exception e) {
        throw new RuntimeException(
                String.format("Error retrieving reference ID from %s.%s", entity.getClass().getSimpleName(), property),
                e);
    }
}
 
Example #24
Source File: CubaPostgreSQLPlatform.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public int getJDBCTypeForSetNull(DatabaseField field) {
    return Types.NULL;
}