Java Code Examples for org.hibernate.type.Type#isEntityType()

The following examples show how to use org.hibernate.type.Type#isEntityType() . These examples are extracted from open source projects. 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
/**
 * Visit a property value. Dispatch to the
 * correct handler for the property type.
 * @param value
 * @param type
 * @throws HibernateException
 */
final Object processValue(Object value, Type type) throws HibernateException {

	if ( type.isCollectionType() ) {
		//even process null collections
		return processCollection( value, (CollectionType) type );
	}
	else if ( type.isEntityType() ) {
		return processEntity( value, (EntityType) type );
	}
	else if ( type.isComponentType() ) {
		return processComponent( value, (CompositeType) type );
	}
	else {
		return null;
	}
}
 
Example 2
private void addAssociationsToTheSetForOneProperty(String name, Type type, String prefix, SessionFactoryImplementor factory) {

		if ( type.isCollectionType() ) {
			CollectionType collType = (CollectionType) type;
			Type assocType = collType.getElementType( factory );
			addAssociationsToTheSetForOneProperty(name, assocType, prefix, factory);
		}
		//ToOne association
		else if ( type.isEntityType() || type.isAnyType() ) {
			associations.add( prefix + name );
		}
		else if ( type.isComponentType() ) {
			CompositeType componentType = (CompositeType) type;
			addAssociationsToTheSetForAllProperties(
					componentType.getPropertyNames(),
					componentType.getSubtypes(),
					(prefix.equals( "" ) ? name : prefix + name) + ".",
					factory);
		}
	}
 
Example 3
@Override
public void registerJoinAlias(Tree aliasNode, PropertyPath path) {
	String alias = aliasNode.getText();
	Type type = propertyHelper.getPropertyType(
		propertyHelper.getEntityNameByAlias( path.getFirstNode().getName() ),
		path.getNodeNamesWithoutAlias() );
	if ( type.isEntityType() ) {
		propertyHelper.registerEntityAlias( type.getName(), alias );
	}
	else if ( type.isAssociationType() ) {
		propertyHelper.registerEntityAlias(
			( (AssociationType) type ).getAssociatedEntityName( sessionFactory ), alias );
	}
	else {
		throw new IllegalArgumentException( "Failed to determine type for alias '" + alias + "'" );
	}
}
 
Example 4
public void end(QueryTranslatorImpl q) throws QueryException {
	if ( !isCollectionValued() ) {
		Type type = getPropertyType();
		if ( type.isEntityType() ) {
			// "finish off" the join
			token( ".", q );
			token( null, q );
		}
		else if ( type.isCollectionType() ) {
			// default to element set if no elements() specified
			token( ".", q );
			token( CollectionPropertyNames.COLLECTION_ELEMENTS, q );
		}
	}
	super.end( q );
}
 
Example 5
@Override
public void finishingCollectionIndex(CollectionIndexDefinition indexDefinition) {
	final Type indexType = indexDefinition.getType();

	if ( indexType.isAnyType() ) {
		// nothing to do because the index graph was not pushed in #startingCollectionIndex.
	}
	else if ( indexType.isEntityType() || indexType.isComponentType() ) {
		// todo : validate the stack?
		final ExpandingFetchSource fetchSource = popFromStack();
		if ( !CollectionFetchableIndex.class.isInstance( fetchSource ) ) {
			throw new WalkingException(
					"CollectionReference did not return an expected index graph : " +
							indexDefinition.getCollectionDefinition().getCollectionPersister().getRole()
			);
		}
	}

	log.tracef(
			"%s Finished collection index graph : %s",
			StringHelper.repeat( "<<", fetchSourceStack.size() ),
			indexDefinition.getCollectionDefinition().getCollectionPersister().getRole()
	);
}
 
Example 6
private EntityLoader createUniqueKeyLoader(
		Type uniqueKeyType,
		String[] columns,
		LoadQueryInfluencers loadQueryInfluencers) {
	if ( uniqueKeyType.isEntityType() ) {
		String className = ( (EntityType) uniqueKeyType ).getAssociatedEntityName();
		uniqueKeyType = getFactory().getMetamodel().entityPersister( className ).getIdentifierType();
	}
	return new EntityLoader(
			this,
			columns,
			uniqueKeyType,
			1,
			LockMode.NONE,
			getFactory(),
			loadQueryInfluencers
	);
}
 
Example 7
private String getElementName(PathExpressionParser.CollectionElement element, QueryTranslatorImpl q) throws QueryException {
	String name;
	if ( element.isOneToMany ) {
		name = element.alias;
	}
	else {
		Type type = element.elementType;
		if ( type.isEntityType() ) { //ie. a many-to-many
			String entityName = ( ( EntityType ) type ).getAssociatedEntityName();
			name = pathExpressionParser.continueFromManyToMany( entityName, element.elementColumns, q );
		}
		else {
			throw new QueryException( "illegally dereferenced collection element" );
		}
	}
	return name;
}
 
Example 8
private boolean hasAssociation(CompositeType componentType) {
	for ( Type subType : componentType.getSubtypes() ) {
		if ( subType.isEntityType() ) {
			return true;
		}
		else if ( subType.isComponentType() && hasAssociation( ( (CompositeType) subType ) ) ) {
			return true;
		}
	}
	return false;
}
 
Example 9
Source Project: lams   File: Cascade.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Cascade an action to a collection
 */
private static void cascadeCollection(
		final CascadingAction action,
		final CascadePoint cascadePoint,
		final EventSource eventSource,
		final int componentPathStackDepth,
		final Object parent,
		final Object child,
		final CascadeStyle style,
		final Object anything,
		final CollectionType type) {
	final CollectionPersister persister = eventSource.getFactory().getCollectionPersister( type.getRole() );
	final Type elemType = persister.getElementType();

	CascadePoint elementsCascadePoint = cascadePoint;
	if ( cascadePoint == CascadePoint.AFTER_INSERT_BEFORE_DELETE ) {
		elementsCascadePoint = CascadePoint.AFTER_INSERT_BEFORE_DELETE_VIA_COLLECTION;
	}

	//cascade to current collection elements
	if ( elemType.isEntityType() || elemType.isAnyType() || elemType.isComponentType() ) {
		cascadeCollectionElements(
			action,
			elementsCascadePoint,
			eventSource,
			componentPathStackDepth,
			parent,
			child,
			type,
			style,
			elemType,
			anything,
			persister.isCascadeDeleteEnabled()
		);
	}
}
 
Example 10
private String fieldType(Column currentColumn) {
	Value value = currentColumn.getValue();
	Type type = value.getType();
	while ( type.isEntityType() || type.isComponentType() ) {
		if ( type.isEntityType() ) {
			type = ( (SimpleValue) value ).getMetadata().getIdentifierType( type.getName() );
		}
		if ( type.isComponentType() ) {
			int i = 0;
			boolean columnFound = false;
			// search which nested property is mapped to the given column
			for ( Iterator<Selectable> ci = value.getColumnIterator(); ci.hasNext(); ++i ) {
				if ( currentColumn.getName().equals( ci.next().getText() ) ) {
					type = ( (ComponentType) type ).getSubtypes()[i];
					columnFound = true;
					break;
				}
			}
			if ( !columnFound ) {
				throw new IllegalArgumentException( "Cannot determine type for column " + currentColumn );
			}
		}
	}
	GridType gridType = serviceRegistry.getService( TypeTranslator.class ).getType( type );
	if ( gridType instanceof EnumType ) {
		return enumFieldType( (EnumType) gridType );
	}
	if ( gridType instanceof YesNoType ) {
		return STRING_CLASS_NAME;
	}
	if ( gridType instanceof NumericBooleanType ) {
		return INTEGER_CLASS_NAME;
	}
	Class<?> returnedClass = type.getReturnedClass();
	if ( Character.class.equals( returnedClass ) ) {
		return STRING_CLASS_NAME;
	}
	return returnedClass.getName();
}
 
Example 11
private EntityLoader createUniqueKeyLoader(Type uniqueKeyType, String[] columns, Map enabledFilters) {
	if ( uniqueKeyType.isEntityType() ) {
		String className = ( ( EntityType ) uniqueKeyType ).getAssociatedEntityName();
		uniqueKeyType = getFactory().getEntityPersister( className ).getIdentifierType();
	}

	return new EntityLoader( this, columns, uniqueKeyType, 1, LockMode.NONE, getFactory(), enabledFilters );
}
 
Example 12
@Override
public void noCascade(
		EventSource session,
		Object parent,
		EntityPersister persister,
		Type propertyType,
		int propertyIndex) {
	if ( propertyType.isEntityType() ) {
		Object child = persister.getPropertyValue( parent, propertyIndex );
		String childEntityName = ((EntityType) propertyType).getAssociatedEntityName( session.getFactory() );

		if ( child != null
				&& !isInManagedState( child, session )
				&& !(child instanceof HibernateProxy) //a proxy cannot be transient and it breaks ForeignKeys.isTransient
				&& ForeignKeys.isTransient( childEntityName, child, null, session ) ) {
			String parentEntityName = persister.getEntityName();
			String propertyName = persister.getPropertyNames()[propertyIndex];
			throw new TransientPropertyValueException(
					"object references an unsaved transient instance - save the transient instance before flushing",
					childEntityName,
					parentEntityName,
					propertyName
			);

		}
	}
}
 
Example 13
/**
 * Return null if the argument is an "unsaved" entity (ie. 
 * one with no existing database row), or the input argument 
 * otherwise. This is how Hibernate avoids foreign key constraint
 * violations.
 */
private Object nullifyTransientReferences(final Object value, final Type type) 
throws HibernateException {
	if ( value == null ) {
		return null;
	}
	else if ( type.isEntityType() ) {
		EntityType entityType = (EntityType) type;
		if ( entityType.isOneToOne() ) {
			return value;
		}
		else {
			String entityName = entityType.getAssociatedEntityName();
			return isNullifiable(entityName, value) ? null : value;
		}
	}
	else if ( type.isAnyType() ) {
		return isNullifiable(null, value) ? null : value;
	}
	else if ( type.isComponentType() ) {
		AbstractComponentType actype = (AbstractComponentType) type;
		Object[] subvalues = actype.getPropertyValues(value, session);
		Type[] subtypes = actype.getSubtypes();
		boolean substitute = false;
		for ( int i = 0; i < subvalues.length; i++ ) {
			Object replacement = nullifyTransientReferences( subvalues[i], subtypes[i] );
			if ( replacement != subvalues[i] ) {
				substitute = true;
				subvalues[i] = replacement;
			}
		}
		if (substitute) actype.setPropertyValues( value, subvalues, session.getEntityMode() );
		return value;
	}
	else {
		return value;
	}
}
 
Example 14
Source Project: yes-cart   File: AuditInterceptor.java    License: Apache License 2.0 4 votes vote down vote up
private void logOperation(final String operation, final Auditable entity, final String user,
                          final Serializable id, final Object[] state, final String[] propertyNames, final Type[] types) {
    final Logger log = LOGS.computeIfAbsent(entity.getClass().getSimpleName(), k ->  LoggerFactory.getLogger("AUDIT." + k));
    if (log.isTraceEnabled()) {

        final String className = entity.getClass().getSimpleName();
        final Set<String> prohibited = prohibitedFields.get(className);

        final StringBuilder line = new StringBuilder();
        line.append(operation);
        line.append(",\"");
        line.append(className);
        line.append("\",\"");
        if (id == null || (id instanceof Number && ((Number) id).longValue() <= 0L)) {
            line.append("N/A");
        } else {
            line.append(id);
        }
        line.append("\",\"");
        line.append(user);
        line.append("\",\"");
        line.append(entity.getGuid());
        line.append('"');
        if (state != null) {
            for (int i = 0; i < propertyNames.length; i++) {
                final Type type = types[i];
                if (type.isCollectionType()) {
                    continue; // skip collections
                }
                final String prop = propertyNames[i];
                final Object value = state[i];

                line.append(",\"");
                line.append(prop);
                line.append(":");

                if (prohibited == null || !prohibited.contains(prop)) {
                    if (type.isEntityType()) {
                        if (Hibernate.isInitialized(value)) {
                            line.append(value);
                        } else {
                            line.append("lazy");
                        }
                    } else {

                        if (value instanceof String) {
                            line.append(((String) value).replace('"','\''));
                        } else {
                            line.append(value);
                        }

                    }
                } else {
                    line.append("[prohibited]");
                }

                line.append("\"");

            }
        }
        log.trace(line.toString());
    }
}
 
Example 15
protected FieldReader getFieldReader(Type[] returnTypes, Map<String,Integer> aliasesMap, JRField field)
{
	FieldReader reader;
	
	String fieldMapping = getFieldMapping(field);
	Integer fieldIdx = aliasesMap.get(fieldMapping);
	if (fieldIdx == null)
	{
		@SuppressWarnings("deprecation")
		int firstNestedIdx = fieldMapping.indexOf(PropertyUtils.NESTED_DELIM);
		
		if (firstNestedIdx < 0)
		{
			throw 
				new JRRuntimeException(
					EXCEPTION_MESSAGE_KEY_UNKNOWN_RETURN_ALIAS,
					new Object[]{fieldMapping});
		}
		
		String fieldAlias = fieldMapping.substring(0, firstNestedIdx);
		String fieldProperty = fieldMapping.substring(firstNestedIdx + 1);
		
		fieldIdx = aliasesMap.get(fieldAlias);
		if (fieldIdx == null)
		{
			throw 
				new JRRuntimeException(
					EXCEPTION_MESSAGE_KEY_NO_FIELD_ALIAS,
					new Object[]{fieldAlias});
		}
		
		Type type = returnTypes[fieldIdx];
		if (!type.isEntityType() && !type.isComponentType())
		{
			throw 
				new JRRuntimeException(
					EXCEPTION_MESSAGE_KEY_FIELD_ALIAS_TYPE_MISMATCH,
					new Object[]{fieldAlias});
		}
		
		reader = new IndexPropertyFieldReader(fieldIdx, fieldProperty);
	}
	else
	{
		reader = new IndexFieldReader(fieldIdx);
	}
	
	return reader;
}
 
Example 16
private CollectionFetchableElement buildElementGraph() {
	final CollectionPersister persister = collectionQuerySpace.getCollectionPersister();
	final Type type = persister.getElementType();
	if ( type.isAssociationType() ) {
		if ( type.isEntityType() ) {
			final EntityPersister elementPersister = persister.getFactory().getEntityPersister(
					( (EntityType) type ).getAssociatedEntityName()
			);
			final ExpandingEntityQuerySpace entityQuerySpace = QuerySpaceHelper.INSTANCE.makeEntityQuerySpace(
					collectionQuerySpace,
					elementPersister,
					CollectionPropertyNames.COLLECTION_ELEMENTS,
					(EntityType) persister.getElementType(),
					collectionQuerySpace.getExpandingQuerySpaces().generateImplicitUid(),
					collectionQuerySpace.canJoinsBeRequired(),
					allowElementJoin
			);
			return new CollectionFetchableElementEntityGraph( this, entityQuerySpace );
		}
		else if ( type.isAnyType() ) {
			return new CollectionFetchableElementAnyGraph( this );
		}
	}
	else if ( type.isComponentType() ) {
		final ExpandingCompositeQuerySpace compositeQuerySpace = QuerySpaceHelper.INSTANCE.makeCompositeQuerySpace(
				collectionQuerySpace,
				new CompositePropertyMapping(
						(CompositeType) persister.getElementType(),
						(PropertyMapping) persister,
						""
				),
				CollectionPropertyNames.COLLECTION_ELEMENTS,
				(CompositeType) persister.getElementType(),
				collectionQuerySpace.getExpandingQuerySpaces().generateImplicitUid(),
				collectionQuerySpace.canJoinsBeRequired(),
				allowElementJoin
		);
		return new CollectionFetchableElementCompositeGraph( this, compositeQuerySpace );
	}

	return null;
}
 
Example 17
/**
 * Cascade to the collection elements
 */
private void cascadeCollectionElements(
		final Object child,
		final CollectionType collectionType,
		final CascadeStyle style,
		final Type elemType,
		final Object anything,
		final boolean isCascadeDeleteEnabled) throws HibernateException {
	// we can't cascade to non-embedded elements
	boolean embeddedElements = eventSource.getEntityMode()!=EntityMode.DOM4J ||
			( (EntityType) collectionType.getElementType( eventSource.getFactory() ) ).isEmbeddedInXML();

	boolean reallyDoCascade = style.reallyDoCascade(action) &&
		embeddedElements && child!=CollectionType.UNFETCHED_COLLECTION;

	if ( reallyDoCascade ) {
		if ( log.isTraceEnabled() ) {
			log.trace( "cascade " + action + " for collection: " + collectionType.getRole() );
		}

		Iterator iter = action.getCascadableChildrenIterator(eventSource, collectionType, child);
		while ( iter.hasNext() ) {
			cascadeProperty(
					iter.next(),
					elemType,
					style,
					anything,
					isCascadeDeleteEnabled
				);
		}

		if ( log.isTraceEnabled() ) {
			log.trace( "done cascade " + action + " for collection: " + collectionType.getRole() );
		}
	}

	final boolean deleteOrphans = style.hasOrphanDelete() &&
			action.deleteOrphans() &&
			elemType.isEntityType() &&
			child instanceof PersistentCollection; //a newly instantiated collection can't have orphans

	if ( deleteOrphans ) { // handle orphaned entities!!
		if ( log.isTraceEnabled() ) {
			log.trace( "deleting orphans for collection: " + collectionType.getRole() );
		}

		// we can do the cast since orphan-delete does not apply to:
		// 1. newly instantiated collections
		// 2. arrays (we can't track orphans for detached arrays)
		final String entityName = collectionType.getAssociatedEntityName( eventSource.getFactory() );
		deleteOrphans( entityName, (PersistentCollection) child );

		if ( log.isTraceEnabled() ) {
			log.trace( "done deleting orphans for collection: " + collectionType.getRole() );
		}
	}
}
 
Example 18
Source Project: lams   File: ForeignKeys.java    License: GNU General Public License v2.0 4 votes vote down vote up
private static void collectNonNullableTransientEntities(
		Nullifier nullifier,
		Object value,
		String propertyName,
		Type type,
		boolean isNullable,
		SharedSessionContractImplementor session,
		NonNullableTransientDependencies nonNullableTransientEntities) {
	if ( value == null ) {
		return;
	}

	if ( type.isEntityType() ) {
		final EntityType entityType = (EntityType) type;
		if ( !isNullable
				&& !entityType.isOneToOne()
				&& nullifier.isNullifiable( entityType.getAssociatedEntityName(), value ) ) {
			nonNullableTransientEntities.add( propertyName, value );
		}
	}
	else if ( type.isAnyType() ) {
		if ( !isNullable && nullifier.isNullifiable( null, value ) ) {
			nonNullableTransientEntities.add( propertyName, value );
		}
	}
	else if ( type.isComponentType() ) {
		final CompositeType actype = (CompositeType) type;
		final boolean[] subValueNullability = actype.getPropertyNullability();
		if ( subValueNullability != null ) {
			final String[] subPropertyNames = actype.getPropertyNames();
			final Object[] subvalues = actype.getPropertyValues( value, session );
			final Type[] subtypes = actype.getSubtypes();
			for ( int j = 0; j < subvalues.length; j++ ) {
				collectNonNullableTransientEntities(
						nullifier,
						subvalues[j],
						subPropertyNames[j],
						subtypes[j],
						subValueNullability[j],
						session,
						nonNullableTransientEntities
				);
			}
		}
	}
}
 
Example 19
FromElement createElementJoin(QueryableCollection queryableCollection) throws SemanticException {
		FromElement elem;

		implied = true; //TODO: always true for now, but not if we later decide to support elements() in the from clause
		inElementsFunction = true;
		Type elementType = queryableCollection.getElementType();
		if ( !elementType.isEntityType() ) {
			throw new IllegalArgumentException( "Cannot create element join for a collection of non-entities!" );
		}
		this.queryableCollection = queryableCollection;
		SessionFactoryHelper sfh = fromClause.getSessionFactoryHelper();
		FromElement destination = null;
		String tableAlias = null;
		EntityPersister entityPersister = queryableCollection.getElementPersister();
		tableAlias = fromClause.getAliasGenerator().createName( entityPersister.getEntityName() );
		String associatedEntityName = entityPersister.getEntityName();
		EntityPersister targetEntityPersister = sfh.requireClassPersister( associatedEntityName );
		// Create the FROM element for the target (the elements of the collection).
		destination = createAndAddFromElement( 
				associatedEntityName,
				classAlias,
				targetEntityPersister,
				( EntityType ) queryableCollection.getElementType(),
				tableAlias
			);
		// If the join is implied, then don't include sub-classes on the element.
		if ( implied ) {
			destination.setIncludeSubclasses( false );
		}
		fromClause.addCollectionJoinFromElementByPath( path, destination );
//		origin.addDestination(destination);
		// Add the query spaces.
		fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );

		CollectionType type = queryableCollection.getCollectionType();
		String role = type.getRole();
		String roleAlias = origin.getTableAlias();

		String[] targetColumns = sfh.getCollectionElementColumns( role, roleAlias );
		AssociationType elementAssociationType = sfh.getElementAssociationType( type );

		// Create the join element under the from element.
		int joinType = JoinFragment.INNER_JOIN;
		JoinSequence joinSequence = sfh.createJoinSequence( implied, elementAssociationType, tableAlias, joinType, targetColumns );
		elem = initializeJoin( path, destination, joinSequence, targetColumns, origin, false );
		elem.setUseFromFragment( true );	// The associated entity is implied, but it must be included in the FROM.
		elem.setCollectionTableAlias( roleAlias );	// The collection alias is the role.
		return elem;
	}
 
Example 20
Source Project: jdal   File: HibernateDao.java    License: Apache License 2.0 4 votes vote down vote up
/** 
 * Create Order from criteria and property path
 * @param criteria the hibernate criteria to apply order on
 * @param propertyPath the property path
 * @return Order 
 */
protected Order createOrder(Criteria criteria, String propertyPath, boolean ascending) {
	Order order = null;
	
	if (propertyPath != null) {
		String sortProperty = PropertyUtils.getPropertyName(propertyPath);
		try {
			if (PropertyUtils.isNested(propertyPath)) {
				String alias = PropertyUtils.getPropertyName(PropertyUtils.getPath(propertyPath));
				// Need to create alias?
				// String alias = HibernateUtils.findAliasForPropertyPath(criteria, propertyPath);
				HibernateUtils.createAlias(criteria, PropertyUtils.getPath(propertyPath));
				sortProperty = alias + PropertyUtils.PROPERTY_SEPARATOR + sortProperty;
			}
			else { // test if property is an entity class
				Type sortType = getClassMetadata().getPropertyType(propertyPath);
				if (sortType.isEntityType()) { // is entity, look for 'name' property
					String[] propertyNames = getClassMetadata(sortType.getReturnedClass()).getPropertyNames();
					for (String name : propertyNames) {
						if ("name".equals(name)) {
							log.info("Found property name on persistent class: " + sortType.getName());
							String newPath = propertyPath + PropertyAccessor.NESTED_PROPERTY_SEPARATOR + "name";
							return createOrder(criteria, newPath, ascending);
						}
					}
				}
			}

			if (log.isDebugEnabled())
				log.debug("Setting order as: " + sortProperty);

			order = ascending ? Order.asc(sortProperty) : Order.desc(sortProperty);
		}
		catch(HibernateException he) {
			log.error("Cannot to create Order for property: " + sortProperty + " for " +
					getEntityClass().getSimpleName(), he);
		}
	}
	else {
		// add default order by id
		ClassMetadata metadata = getClassMetadata();
		if (metadata != null)
			order = Order.asc(metadata.getIdentifierPropertyName());
	}

	return order;
	
}