org.hibernate.type.EntityType Java Examples

The following examples show how to use org.hibernate.type.EntityType. 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: AbstractPropertyMapping.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void initIdentifierPropertyPaths(
		final String path, 
		final EntityType etype, 
		final String[] columns, 
		final Mapping factory) throws MappingException {

	Type idtype = etype.getIdentifierOrUniqueKeyType( factory );
	String idPropName = etype.getIdentifierOrUniqueKeyPropertyName(factory);
	boolean hasNonIdentifierPropertyNamedId = hasNonIdentifierPropertyNamedId( etype, factory );

	if ( etype.isReferenceToPrimaryKey() ) {
		if ( !hasNonIdentifierPropertyNamedId ) {
			String idpath1 = extendPath(path, EntityPersister.ENTITY_ID);
			addPropertyPath(idpath1, idtype, columns, null);
			initPropertyPaths(idpath1, idtype, columns, null, factory);
		}
	}

	if (idPropName!=null) {
		String idpath2 = extendPath(path, idPropName);
		addPropertyPath(idpath2, idtype, columns, null);
		initPropertyPaths(idpath2, idtype, columns, null, factory);
	}
}
 
Example #2
Source File: JoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Does the mapping, and Hibernate default semantics, specify that
 * this association should be fetched by outer joining
 */
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type) 
throws MappingException {
	if ( !type.isEntityType() && !type.isCollectionType() ) {
		return false;
	}
	else {
		if (config==FetchMode.JOIN) return true;
		if (config==FetchMode.SELECT) return false;
		if ( type.isEntityType() ) {
			//TODO: look at the owning property and check that it 
			//      isn't lazy (by instrumentation)
			EntityType entityType =(EntityType) type;
			EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
			return !persister.hasProxy();
		}
		else {
			return false;
		}
	}
}
 
Example #3
Source File: MapEntryNode.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void determineValueSelectExpressions(QueryableCollection collectionPersister, List selections) {
	AliasGenerator aliasGenerator = new LocalAliasGenerator( 1 );
	appendSelectExpressions( collectionPersister.getElementColumnNames(), selections, aliasGenerator );
	Type valueType = collectionPersister.getElementType();
	if ( valueType.isAssociationType() ) {
		EntityType valueEntityType = (EntityType) valueType;
		Queryable valueEntityPersister = (Queryable) sfi().getEntityPersister(
				valueEntityType.getAssociatedEntityName( sfi() )
		);
		SelectFragment fragment = valueEntityPersister.propertySelectFragmentFragment(
				elementTableAlias(),
				null,
				false
		);
		appendSelectExpressions( fragment, selections, aliasGenerator );
	}
}
 
Example #4
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Does the mapping, and Hibernate default semantics, specify that
 * this association should be fetched by outer joining
 */
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type)
		throws MappingException {
	if ( !type.isEntityType() && !type.isCollectionType() ) {
		return false;
	}
	else {
		if ( config == FetchMode.JOIN ) {
			return true;
		}
		if ( config == FetchMode.SELECT ) {
			return false;
		}
		if ( type.isEntityType() ) {
			//TODO: look at the owning property and check that it 
			//      isn't lazy (by instrumentation)
			EntityType entityType = (EntityType) type;
			EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
			return !persister.hasProxy();
		}
		else {
			return false;
		}
	}
}
 
Example #5
Source File: EntityJoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Integer locateKeyManyToOneTargetIndex(OuterJoinableAssociation joinWithCompositeId, EntityType keyManyToOneType) {
	// the lhs (if one) is a likely candidate
	if ( joinWithCompositeId.getLhsAlias() != null ) {
		final OuterJoinableAssociation lhs = associationsByAlias.get( joinWithCompositeId.getLhsAlias() );
		if ( keyManyToOneType.getAssociatedEntityName( factory ).equals( lhs.getJoinableType().getAssociatedEntityName( factory ) ) ) {
			return positionsByAlias.get( lhs.getRhsAlias() );
		}
	}
	// otherwise, seek out OuterJoinableAssociation which are RHS of given OuterJoinableAssociation
	// (joinWithCompositeId)
	for ( OuterJoinableAssociation oja : associationsByAlias.values() ) {
		if ( oja.getLhsAlias() != null && oja.getLhsAlias().equals( joinWithCompositeId.getRhsAlias() ) ) {
			if ( keyManyToOneType.equals( oja.getJoinableType() ) ) {
				return positionsByAlias.get( oja.getLhsAlias() );
			}
		}
	}
	return null;
}
 
Example #6
Source File: WhereParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #7
Source File: EntityJoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void findKeyManyToOneTargetIndices(
		ArrayList<Integer> keyManyToOneTargetIndices,
		OuterJoinableAssociation joinWithCompositeId,
		CompositeType componentType) {
	for ( Type subType : componentType.getSubtypes() ) {
		if ( subType.isEntityType() ) {
			Integer index = locateKeyManyToOneTargetIndex( joinWithCompositeId, (EntityType) subType );
			if ( index != null ) {
				keyManyToOneTargetIndices.add( index );
			}
		}
		else if ( subType.isComponentType() ) {
			findKeyManyToOneTargetIndices(
					keyManyToOneTargetIndices,
					joinWithCompositeId,
					(CompositeType) subType
			);
		}
	}
}
 
Example #8
Source File: IteratorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void remove() {
	if (!single) {
		throw new UnsupportedOperationException("Not a single column hibernate query result set");
	}
	if (currentResult==null) {
		throw new IllegalStateException("Called Iterator.remove() before next()");
	}
	if ( !( types[0] instanceof EntityType ) ) {
		throw new UnsupportedOperationException("Not an entity");
	}
	
	session.delete( 
			( (EntityType) types[0] ).getAssociatedEntityName(), 
			currentResult,
			false,
	        null
		);
}
 
Example #9
Source File: AbstractVisitor.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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, (AbstractComponentType) type );
	}
	else {
		return null;
	}
}
 
Example #10
Source File: FromElementFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private FromElement createJoin(
		String entityClass,
		String tableAlias,
		JoinSequence joinSequence,
		EntityType type,
		boolean manyToMany) throws SemanticException {
	//  origin, path, implied, columns, classAlias,
	EntityPersister entityPersister = fromClause.getSessionFactoryHelper().requireClassPersister( entityClass );
	FromElement destination = createAndAddFromElement(
			entityClass,
			classAlias,
			entityPersister,
			type,
			tableAlias
	);
	return initializeJoin( path, destination, joinSequence, getColumns(), origin, manyToMany );
}
 
Example #11
Source File: ResultSetProcessingContextImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void registerNonExists(EntityFetch fetch) {
	final EntityType fetchedType = fetch.getFetchedType();
	if ( ! fetchedType.isOneToOne() ) {
		return;
	}

	final EntityReferenceProcessingState fetchOwnerState = getOwnerProcessingState( fetch );
	if ( fetchOwnerState == null ) {
		throw new IllegalStateException( "Could not locate fetch owner state" );
	}

	final EntityKey ownerEntityKey = fetchOwnerState.getEntityKey();
	if ( ownerEntityKey == null ) {
		throw new IllegalStateException( "Could not locate fetch owner EntityKey" );
	}

	session.getPersistenceContext().addNullProperty(
			ownerEntityKey,
			fetchedType.getPropertyName()
	);
}
 
Example #12
Source File: FromElementFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
FromElement addFromElement() throws SemanticException {
	final FromClause parentFromClause = fromClause.getParentFromClause();
	if ( parentFromClause != null ) {
		// Look up class name using the first identifier in the path.
		final String pathAlias = PathHelper.getAlias( path );
		final FromElement parentFromElement = parentFromClause.getFromElement( pathAlias );
		if ( parentFromElement != null ) {
			return createFromElementInSubselect( path, pathAlias, parentFromElement, classAlias );
		}
	}

	final EntityPersister entityPersister = fromClause.getSessionFactoryHelper().requireClassPersister( path );

	final FromElement elem = createAndAddFromElement(
			path,
			classAlias,
			entityPersister,
			(EntityType) ( (Queryable) entityPersister ).getType(),
			null
	);

	// Add to the query spaces.
	fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );

	return elem;
}
 
Example #13
Source File: AliasResolutionContextImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private EntityReferenceAliases createCollectionElementAliases(
		CollectionPersister collectionPersister,
		String tableAlias,
		String elementQuerySpaceUid) {

	if ( !collectionPersister.getElementType().isEntityType() ) {
		return null;
	}
	else {
		final EntityType entityElementType = (EntityType) collectionPersister.getElementType();
		return generateEntityReferenceAliases(
				elementQuerySpaceUid,
				tableAlias,
				(EntityPersister) entityElementType.getAssociatedJoinable( sessionFactory() )
		);
	}
}
 
Example #14
Source File: DotNode.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Is the given property name a reference to the primary key of the associated
 * entity construed by the given entity type?
 * <p/>
 * For example, consider a fragment like order.customer.id
 * (where order is a from-element alias).  Here, we'd have:
 * propertyName = "id" AND
 * owningType = ManyToOneType(Customer)
 * and are being asked to determine whether "customer.id" is a reference
 * to customer's PK...
 *
 * @param propertyName The name of the property to check.
 * @param owningType The type represeting the entity "owning" the property
 *
 * @return True if propertyName references the entity's (owningType->associatedEntity)
 *         primary key; false otherwise.
 */
private boolean isReferenceToPrimaryKey(String propertyName, EntityType owningType) {
	EntityPersister persister = getSessionFactoryHelper()
			.getFactory()
			.getEntityPersister( owningType.getAssociatedEntityName() );
	if ( persister.getEntityMetamodel().hasNonIdentifierPropertyNamedId() ) {
		// only the identifier property field name can be a reference to the associated entity's PK...
		return propertyName.equals( persister.getIdentifierPropertyName() ) && owningType.isReferenceToPrimaryKey();
	}
	// here, we have two possibilities:
	// 1) the property-name matches the explicitly identifier property name
	// 2) the property-name matches the implicit 'id' property name
	// the referenced node text is the special 'id'
	if ( EntityPersister.ENTITY_ID.equals( propertyName ) ) {
		return owningType.isReferenceToPrimaryKey();
	}
	String keyPropertyName = getSessionFactoryHelper().getIdentifierOrUniqueKeyPropertyName( owningType );
	return keyPropertyName != null && keyPropertyName.equals( propertyName ) && owningType.isReferenceToPrimaryKey();
}
 
Example #15
Source File: JoinHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public JoinDefinedByMetadata createEntityJoin(
		QuerySpace leftHandSide,
		String lhsPropertyName,
		EntityQuerySpace rightHandSide,
		boolean rightHandSideRequired,
		EntityType joinedPropertyType,
		SessionFactoryImplementor sessionFactory) {
	return new JoinImpl(
			leftHandSide,
			lhsPropertyName,
			rightHandSide,
			determineRhsColumnNames( joinedPropertyType, sessionFactory ),
			joinedPropertyType,
			rightHandSideRequired
	);
}
 
Example #16
Source File: WhereParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #17
Source File: FromElement.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void doInitialize(FromClause fromClause, String tableAlias, String className, String classAlias,
						  EntityPersister persister, EntityType type) {
	if ( initialized ) {
		throw new IllegalStateException( "Already initialized!!" );
	}
	this.fromClause = fromClause;
	this.tableAlias = tableAlias;
	this.className = className;
	this.classAlias = classAlias;
	this.elementType = new FromElementType( this, persister, type );
	// Register the FromElement with the FROM clause, now that we have the names and aliases.
	fromClause.registerFromElement( this );
	if ( log.isDebugEnabled() ) {
		log.debug( fromClause + " :  " + className + " ("
				+ ( classAlias == null ? "no alias" : classAlias ) + ") -> " + tableAlias );
	}
}
 
Example #18
Source File: AbstractExpandingFetchSource.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public BidirectionalEntityReference buildBidirectionalEntityReference(
		AssociationAttributeDefinition attributeDefinition,
		FetchStrategy fetchStrategy,
		EntityReference targetEntityReference) {
	final EntityType fetchedType = (EntityType) attributeDefinition.getType();
	final EntityPersister fetchedPersister = attributeDefinition.toEntityDefinition().getEntityPersister();

	if ( fetchedPersister == null ) {
		throw new WalkingException(
				String.format(
						"Unable to locate EntityPersister [%s] for bidirectional entity reference [%s]",
						fetchedType.getAssociatedEntityName(),
						attributeDefinition.getName()
				)
		);
	}

	final BidirectionalEntityReference bidirectionalEntityReference =
			new BidirectionalEntityReferenceImpl( this, attributeDefinition, targetEntityReference );
	addBidirectionalEntityReference( bidirectionalEntityReference );
	return bidirectionalEntityReference;
}
 
Example #19
Source File: IteratorImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void remove() {
	if ( !single ) {
		throw new UnsupportedOperationException( "Not a single column hibernate query result set" );
	}
	if ( currentResult == null ) {
		throw new IllegalStateException( "Called Iterator.remove() before next()" );
	}
	if ( !( types[0] instanceof EntityType ) ) {
		throw new UnsupportedOperationException( "Not an entity" );
	}

	session.delete(
			( (EntityType) types[0] ).getAssociatedEntityName(),
			currentResult,
			false,
			null
	);
}
 
Example #20
Source File: Cascade.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Cascade an action to a to-one association or any type
 */
private static void cascadeToOne(
		final CascadingAction action,
		final EventSource eventSource,
		final Object parent,
		final Object child,
		final Type type,
		final CascadeStyle style,
		final Object anything,
		final boolean isCascadeDeleteEnabled) {
	final String entityName = type.isEntityType()
			? ( (EntityType) type ).getAssociatedEntityName()
			: null;
	if ( style.reallyDoCascade( action ) ) {
		//not really necessary, but good for consistency...
		eventSource.getPersistenceContext().addChildParent( child, parent );
		try {
			action.cascade( eventSource, child, entityName, anything, isCascadeDeleteEnabled );
		}
		finally {
			eventSource.getPersistenceContext().removeChildParent( child );
		}
	}
}
 
Example #21
Source File: AbstractPropertyMapping.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected void initIdentifierPropertyPaths(
		final String path,
		final EntityType etype,
		final String[] columns,
		final String[] columnReaders,
		final String[] columnReaderTemplates,
		final Mapping factory) throws MappingException {

	Type idtype = etype.getIdentifierOrUniqueKeyType( factory );
	String idPropName = etype.getIdentifierOrUniqueKeyPropertyName( factory );
	boolean hasNonIdentifierPropertyNamedId = hasNonIdentifierPropertyNamedId( etype, factory );

	if ( etype.isReferenceToPrimaryKey() ) {
		if ( !hasNonIdentifierPropertyNamedId ) {
			String idpath1 = extendPath( path, EntityPersister.ENTITY_ID );
			addPropertyPath( idpath1, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
			initPropertyPaths( idpath1, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
		}
	}

	if ( idPropName != null ) {
		String idpath2 = extendPath( path, idPropName );
		addPropertyPath( idpath2, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
		initPropertyPaths( idpath2, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
	}
}
 
Example #22
Source File: FromElementFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private FromElement createEntityAssociation(
        String role,
        String roleAlias,
        int joinType) throws SemanticException {
	FromElement elem;
	Queryable entityPersister = ( Queryable ) queryableCollection.getElementPersister();
	String associatedEntityName = entityPersister.getEntityName();
	// Get the class name of the associated entity.
	if ( queryableCollection.isOneToMany() ) {
		if ( log.isDebugEnabled() ) {
			log.debug( "createEntityAssociation() : One to many - path = " + path + " role = " + role + " associatedEntityName = " + associatedEntityName );
		}
		JoinSequence joinSequence = createJoinSequence( roleAlias, joinType );

		elem = createJoin( associatedEntityName, roleAlias, joinSequence, ( EntityType ) queryableCollection.getElementType(), false );
	}
	else {
		if ( log.isDebugEnabled() ) {
			log.debug( "createManyToMany() : path = " + path + " role = " + role + " associatedEntityName = " + associatedEntityName );
		}
		elem = createManyToMany( role, associatedEntityName,
				roleAlias, entityPersister, ( EntityType ) queryableCollection.getElementType(), joinType );
		fromClause.getWalker().addQuerySpaces( queryableCollection.getCollectionSpaces() );
	}
	elem.setCollectionTableAlias( roleAlias );
	return elem;
}
 
Example #23
Source File: FromElementFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private FromElement createAndAddFromElement(
		String className,
		String classAlias,
		EntityPersister entityPersister,
		EntityType type,
		String tableAlias) {
	if ( !( entityPersister instanceof Joinable ) ) {
		throw new IllegalArgumentException( "EntityPersister " + entityPersister + " does not implement Joinable!" );
	}
	FromElement element = createFromElement( entityPersister );
	initializeAndAddFromElement( element, className, classAlias, entityPersister, type, tableAlias );
	return element;
}
 
Example #24
Source File: ForeignGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @see org.hibernate.id.IdentifierGenerator#generate(org.hibernate.engine.SessionImplementor, java.lang.Object)
 */
public Serializable generate(SessionImplementor sessionImplementor, Object object)
throws HibernateException {
	
	Session session = (Session) sessionImplementor;

	Object associatedObject = sessionImplementor.getFactory()
	        .getClassMetadata( entityName )
	        .getPropertyValue( object, propertyName, session.getEntityMode() );
	
	if ( associatedObject == null ) {
		throw new IdentifierGenerationException(
				"attempted to assign id from null one-to-one property: " + 
				propertyName
			);
	}
	
	EntityType type = (EntityType) sessionImplementor.getFactory()
       	.getClassMetadata( entityName )
       	.getPropertyType( propertyName );

	Serializable id;
	try {
		id = ForeignKeys.getEntityIdentifierIfNotUnsaved(
				type.getAssociatedEntityName(), 
				associatedObject, 
				sessionImplementor
			); 
	}
	catch (TransientObjectException toe) {
		id = session.save( type.getAssociatedEntityName(), associatedObject );
	}

	if ( session.contains(object) ) {
		//abort the save (the object is already saved by a circular cascade)
		return IdentifierGeneratorFactory.SHORT_CIRCUIT_INDICATOR;
		//throw new IdentifierGenerationException("save associated object first, or disable cascade for inverse association");
	}
	return id;
}
 
Example #25
Source File: NaturalIdCacheKey.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a new key for a caching natural identifier resolutions into the second level cache.
 * @param naturalIdValues The naturalIdValues associated with the cached data
 * @param propertyTypes
 * @param naturalIdPropertyIndexes
 * @param session The originating session
 */
public NaturalIdCacheKey(
		final Object[] naturalIdValues,
		Type[] propertyTypes, int[] naturalIdPropertyIndexes, final String entityName,
		final SharedSessionContractImplementor session) {

	this.entityName = entityName;
	this.tenantId = session.getTenantIdentifier();

	this.naturalIdValues = new Serializable[naturalIdValues.length];

	final SessionFactoryImplementor factory = session.getFactory();

	final int prime = 31;
	int result = 1;
	result = prime * result + ( ( this.entityName == null ) ? 0 : this.entityName.hashCode() );
	result = prime * result + ( ( this.tenantId == null ) ? 0 : this.tenantId.hashCode() );
	for ( int i = 0; i < naturalIdValues.length; i++ ) {
		final int naturalIdPropertyIndex = naturalIdPropertyIndexes[i];
		final Type type = propertyTypes[naturalIdPropertyIndex];
		final Object value = naturalIdValues[i];

		result = prime * result + (value != null ? type.getHashCode( value, factory ) : 0);

		// The natural id may not be fully resolved in some situations.  See HHH-7513 for one of them
		// (re-attaching a mutable natural id uses a database snapshot and hydration does not resolve associations).
		// TODO: The snapshot should probably be revisited at some point.  Consider semi-resolving, hydrating, etc.
		if (type instanceof EntityType && type.getSemiResolvedType( factory ).getReturnedClass().isInstance( value )) {
			this.naturalIdValues[i] = (Serializable) value;
		}
		else {
			this.naturalIdValues[i] = type.disassemble( value, session, null );
		}
	}

	this.hashCode = result;
	initTransients();
}
 
Example #26
Source File: SessionFactoryHelper.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine the name of the property for the entity encapsulated by the
 * given type which represents the id or unique-key.
 *
 * @param entityType The type representing the entity.
 * @return The corresponding property name
 * @throws QueryException Indicates such a property could not be found.
 */
public String getIdentifierOrUniqueKeyPropertyName(EntityType entityType) {
	try {
		return entityType.getIdentifierOrUniqueKeyPropertyName( sfi );
	}
	catch ( MappingException me ) {
		throw new QueryException( me );
	}
}
 
Example #27
Source File: ManyToOne.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void createPropertyRefConstraints(Map persistentClasses) {
	if (referencedPropertyName!=null) {
		PersistentClass pc = (PersistentClass) persistentClasses.get(getReferencedEntityName() );
		
		Property property = pc.getReferencedProperty( getReferencedPropertyName() );
		
		if (property==null) {
			throw new MappingException(
					"Could not find property " + 
					getReferencedPropertyName() + 
					" on " + 
					getReferencedEntityName() 
				);
		} 
		else {
			if ( !hasFormula() && !"none".equals( getForeignKeyName() ) ) {
				java.util.List refColumns = new ArrayList();
				Iterator iter = property.getColumnIterator();
				while ( iter.hasNext() ) {
					Column col = (Column) iter.next();
					refColumns.add( col );							
				}
				
				ForeignKey fk = getTable().createForeignKey( 
						getForeignKeyName(), 
						getConstraintColumns(), 
						( (EntityType) getType() ).getAssociatedEntityName(), 
						refColumns 
					);
				fk.setCascadeDeleteEnabled(isCascadeDeleteEnabled() );
			}
		}
	}
}
 
Example #28
Source File: ForeignKeys.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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.
 *
 * @param value An entity attribute value
 * @param type An entity attribute type
 *
 * @return {@code null} if the argument is an unsaved entity; otherwise return the argument.
 */
private Object nullifyTransientReferences(final Object value, final Type type) {
	if ( value == null ) {
		return null;
	}
	else if ( type.isEntityType() ) {
		final EntityType entityType = (EntityType) type;
		if ( entityType.isOneToOne() ) {
			return value;
		}
		else {
			final String entityName = entityType.getAssociatedEntityName();
			return isNullifiable( entityName, value ) ? null : value;
		}
	}
	else if ( type.isAnyType() ) {
		return isNullifiable( null, value ) ? null : value;
	}
	else if ( type.isComponentType() ) {
		final CompositeType actype = (CompositeType) type;
		final Object[] subvalues = actype.getPropertyValues( value, session );
		final Type[] subtypes = actype.getSubtypes();
		boolean substitute = false;
		for ( int i = 0; i < subvalues.length; i++ ) {
			final Object replacement = nullifyTransientReferences( subvalues[i], subtypes[i] );
			if ( replacement != subvalues[i] ) {
				substitute = true;
				subvalues[i] = replacement;
			}
		}
		if ( substitute ) {
			// todo : need to account for entity mode on the CompositeType interface :(
			actype.setPropertyValues( value, subvalues, EntityMode.POJO );
		}
		return value;
	}
	else {
		return value;
	}
}
 
Example #29
Source File: CascadingActions.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 #30
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void checkIdClass(
		final EntityPersister persister,
		final LoadEvent event,
		final LoadEventListener.LoadType loadType,
		final Class idClass) {
			// we may have the kooky jpa requirement of allowing find-by-id where
		// "id" is the "simple pk value" of a dependent objects parent.  This
		// is part of its generally goofy "derived identity" "feature"
		if ( persister.getEntityMetamodel().getIdentifierProperty().isEmbedded() ) {
			final EmbeddedComponentType dependentIdType =
					(EmbeddedComponentType) persister.getEntityMetamodel().getIdentifierProperty().getType();
			if ( dependentIdType.getSubtypes().length == 1 ) {
				final Type singleSubType = dependentIdType.getSubtypes()[0];
				if ( singleSubType.isEntityType() ) {
					final EntityType dependentParentType = (EntityType) singleSubType;
					final Type dependentParentIdType = dependentParentType.getIdentifierOrUniqueKeyType( event.getSession().getFactory() );
					if ( dependentParentIdType.getReturnedClass().isInstance( event.getEntityId() ) ) {
						// yep that's what we have...
						loadByDerivedIdentitySimplePkValue(
								event,
								loadType,
								persister,
								dependentIdType,
								event.getSession().getFactory().getEntityPersister( dependentParentType.getAssociatedEntityName() )
						);
						return;
					}
				}
			}
		}
		throw new TypeMismatchException(
				"Provided id of the wrong type for class " + persister.getEntityName() + ". Expected: " + idClass
						+ ", got " + event.getEntityId().getClass()
		);
}