Java Code Examples for org.hibernate.persister.entity.EntityPersister.getIdentifier()

The following are Jave code examples for showing how to use getIdentifier() of the org.hibernate.persister.entity.EntityPersister class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: StatelessSessionImpl.java   View Source Code Vote up 6 votes
@Override
public void update(String entityName, Object entity) {
	errorIfClosed();
	EntityPersister persister = getEntityPersister(entityName, entity);
	Serializable id = persister.getIdentifier( entity, this );
	Object[] state = persister.getPropertyValues( entity );
	Object oldVersion;
	if ( persister.isVersioned() ) {
		oldVersion = persister.getVersion( entity );
		Object newVersion = Versioning.increment( oldVersion, persister.getVersionType(), this );
		Versioning.setVersion(state, newVersion, persister);
		persister.setPropertyValues( entity, state );
	}
	else {
		oldVersion = null;
	}
	persister.update(id, state, null, false, null, oldVersion, entity, null, this);
}
 
Example 2
Project: lams   File: DefaultFlushEntityEventListener.java   View Source Code Vote up 6 votes
/**
 * make sure user didn't mangle the id
 */
public void checkId(Object object, EntityPersister persister, Serializable id, SessionImplementor session)
		throws HibernateException {

	if ( id != null && id instanceof DelayedPostInsertIdentifier ) {
		// this is a situation where the entity id is assigned by a post-insert generator
		// and was saved outside the transaction forcing it to be delayed
		return;
	}

	if ( persister.canExtractIdOutOfEntity() ) {

		Serializable oid = persister.getIdentifier( object, session );
		if ( id == null ) {
			throw new AssertionFailure( "null id in " + persister.getEntityName() + " entry (don't flush the Session after an exception occurs)" );
		}
		if ( !persister.getIdentifierType().isEqual( id, oid, session.getFactory() ) ) {
			throw new HibernateException(
					"identifier of an instance of " + persister.getEntityName() + " was altered from "
							+ id + " to " + oid
			);
		}
	}

}
 
Example 3
Project: lams   File: DefaultSaveOrUpdateEventListener.java   View Source Code Vote up 6 votes
/**
 * Determine the id to use for updating.
 *
 * @param entity The entity.
 * @param persister The entity persister
 * @param requestedId The requested identifier
 * @param session The session
 *
 * @return The id.
 *
 * @throws TransientObjectException If the entity is considered transient.
 */
protected Serializable getUpdateId(
		Object entity,
		EntityPersister persister,
		Serializable requestedId,
		SessionImplementor session) {
	// use the id assigned to the instance
	Serializable id = persister.getIdentifier( entity, session );
	if ( id == null ) {
		// assume this is a newly instantiated transient object
		// which should be saved rather than updated
		throw new TransientObjectException(
				"The given object has a null identifier: " +
						persister.getEntityName()
		);
	}
	else {
		return id;
	}

}
 
Example 4
Project: lams   File: CollectionType.java   View Source Code Vote up 6 votes
/**
 * Get the id value from the owning entity key, usually the same as the key, but might be some
 * other property, in the case of property-ref
 *
 * @param key The collection owner key
 * @param session The session from which the request is originating.
 * @return The collection owner's id, if it can be obtained from the key;
 * otherwise, null is returned
 */
public Serializable getIdOfOwnerOrNull(Serializable key, SessionImplementor session) {
	Serializable ownerId = null;
	if ( foreignKeyPropertyName == null ) {
		ownerId = key;
	}
	else {
		Type keyType = getPersister( session ).getKeyType();
		EntityPersister ownerPersister = getPersister( session ).getOwnerEntityPersister();
		// TODO: Fix this so it will work for non-POJO entity mode
		Class ownerMappedClass = ownerPersister.getMappedClass();
		if ( ownerMappedClass.isAssignableFrom( keyType.getReturnedClass() ) &&
				keyType.getReturnedClass().isInstance( key ) ) {
			// the key is the owning entity itself, so get the ID from the key
			ownerId = ownerPersister.getIdentifier( key, session );
		}
		else {
			// TODO: check if key contains the owner ID
		}
	}
	return ownerId;
}
 
Example 5
Project: lams   File: IdTransferringMergeEventListener.java   View Source Code Vote up 5 votes
/**
 * Hibernate 3.1 implementation of ID transferral.
 */
@Override
protected void entityIsTransient(MergeEvent event, Map copyCache) {
	super.entityIsTransient(event, copyCache);
	SessionImplementor session = event.getSession();
	EntityPersister persister = session.getEntityPersister(event.getEntityName(), event.getEntity());
	// Extract id from merged copy (which is currently registered with Session).
	Serializable id = persister.getIdentifier(event.getResult(), session.getEntityMode());
	// Set id on original object (which remains detached).
	persister.setIdentifier(event.getOriginal(), id, session.getEntityMode());
}
 
Example 6
Project: lams   File: StatelessSessionImpl.java   View Source Code Vote up 5 votes
@Override
public void delete(String entityName, Object entity) {
	errorIfClosed();
	EntityPersister persister = getEntityPersister(entityName, entity);
	Serializable id = persister.getIdentifier( entity, this );
	Object version = persister.getVersion( entity );
	persister.delete(id, version, entity, this);
}
 
Example 7
Project: lams   File: StatelessSessionImpl.java   View Source Code Vote up 5 votes
@Override
	public void refresh(String entityName, Object entity, LockMode lockMode) {
		final EntityPersister persister = this.getEntityPersister( entityName, entity );
		final Serializable id = persister.getIdentifier( entity, this );
		if ( LOG.isTraceEnabled() ) {
			LOG.tracev( "Refreshing transient {0}", MessageHelper.infoString( persister, id, this.getFactory() ) );
		}
		// TODO : can this ever happen???
//		EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
//		if ( source.getPersistenceContext().getEntry( key ) != null ) {
//			throw new PersistentObjectException(
//					"attempted to refresh transient instance when persistent " +
//					"instance was already associated with the Session: " +
//					MessageHelper.infoString( persister, id, source.getFactory() )
//			);
//		}

		if ( persister.hasCache() ) {
			final CacheKey ck = generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
			persister.getCacheAccessStrategy().evict( ck );
		}

		String previousFetchProfile = this.getFetchProfile();
		Object result = null;
		try {
			this.setFetchProfile( "refresh" );
			result = persister.load( id, entity, lockMode, this );
		}
		finally {
			this.setFetchProfile( previousFetchProfile );
		}
		UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() );
	}
 
Example 8
Project: lams   File: DefaultLockEventListener.java   View Source Code Vote up 5 votes
/**
 * Handle the given lock event.
 *
 * @param event The lock event to be handled.
 * @throws HibernateException
 */
public void onLock(LockEvent event) throws HibernateException {

	if ( event.getObject() == null ) {
		throw new NullPointerException( "attempted to lock null" );
	}

	if ( event.getLockMode() == LockMode.WRITE ) {
		throw new HibernateException( "Invalid lock mode for lock()" );
	}

	if ( event.getLockMode() == LockMode.UPGRADE_SKIPLOCKED ) {
		LOG.explicitSkipLockedLockCombo();
	}

	SessionImplementor source = event.getSession();
	
	Object entity = source.getPersistenceContext().unproxyAndReassociate( event.getObject() );
	//TODO: if object was an uninitialized proxy, this is inefficient,
	//      resulting in two SQL selects
	
	EntityEntry entry = source.getPersistenceContext().getEntry(entity);
	if (entry==null) {
		final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );
		final Serializable id = persister.getIdentifier( entity, source );
		if ( !ForeignKeys.isNotTransient( event.getEntityName(), entity, Boolean.FALSE, source ) ) {
			throw new TransientObjectException(
					"cannot lock an unsaved transient instance: " +
					persister.getEntityName()
			);
		}

		entry = reassociate(event, entity, id, persister);
		cascadeOnLock(event, persister, entity);
	}

	upgradeLock( entity, entry, event.getLockOptions(), event.getSession() );
}
 
Example 9
Project: lams   File: DefaultMergeEventListener.java   View Source Code Vote up 5 votes
protected void entityIsTransient(MergeEvent event, Map copyCache) {

		LOG.trace( "Merging transient instance" );

		final Object entity = event.getEntity();
		final EventSource source = event.getSession();

		final String entityName = event.getEntityName();
		final EntityPersister persister = source.getEntityPersister( entityName, entity );

		final Serializable id = persister.hasIdentifierProperty() ?
				persister.getIdentifier( entity, source ) :
				null;
		if ( copyCache.containsKey( entity ) ) {
			persister.setIdentifier( copyCache.get( entity ), id, source );
		}
		else {
			( (MergeContext) copyCache ).put( entity, source.instantiate( persister, id ), true ); //before cascade!
		}
		final Object copy = copyCache.get( entity );

		// cascade first, so that all unsaved objects get their
		// copy created before we actually copy
		//cascadeOnMerge(event, persister, entity, copyCache, Cascades.CASCADE_BEFORE_MERGE);
		super.cascadeBeforeSave( source, persister, entity, copyCache );
		copyValues( persister, entity, copy, source, copyCache, ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT );

		saveTransientEntity( copy, entityName, event.getRequestedId(), source, copyCache );

		// cascade first, so that all unsaved objects get their
		// copy created before we actually copy
		super.cascadeAfterSave( source, persister, entity, copyCache );
		copyValues( persister, entity, copy, source, copyCache, ForeignKeyDirection.FOREIGN_KEY_TO_PARENT );

		event.setResult( copy );
	}
 
Example 10
Project: lams   File: DefaultMergeEventListener.java   View Source Code Vote up 5 votes
private boolean existsInDatabase(Object entity, EventSource source, EntityPersister persister) {
	EntityEntry entry = source.getPersistenceContext().getEntry( entity );
	if ( entry == null ) {
		Serializable id = persister.getIdentifier( entity, source );
		if ( id != null ) {
			final EntityKey key = source.generateEntityKey( id, persister );
			final Object managedEntity = source.getPersistenceContext().getEntity( key );
			entry = source.getPersistenceContext().getEntry( managedEntity );
		}
	}

	return entry != null && entry.isExistsInDatabase();
}
 
Example 11
Project: lams   File: StatefulPersistenceContext.java   View Source Code Vote up 4 votes
@Override
public Object getCollectionOwner(Serializable key, CollectionPersister collectionPersister) throws MappingException {
	// todo : we really just need to add a split in the notions of:
	//		1) collection key
	//		2) collection owner key
	// these 2 are not always the same.  Same is true in the case of ToOne associations with property-ref...
	final EntityPersister ownerPersister = collectionPersister.getOwnerEntityPersister();
	if ( ownerPersister.getIdentifierType().getReturnedClass().isInstance( key ) ) {
		return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) );
	}

	// we have a property-ref type mapping for the collection key.  But that could show up a few ways here...
	//
	//		1) The incoming key could be the entity itself...
	if ( ownerPersister.isInstance( key ) ) {
		final Serializable owenerId = ownerPersister.getIdentifier( key, session );
		if ( owenerId == null ) {
			return null;
		}
		return getEntity( session.generateEntityKey( owenerId, ownerPersister ) );
	}

	final CollectionType collectionType = collectionPersister.getCollectionType();

	//		2) The incoming key is most likely the collection key which we need to resolve to the owner key
	//			find the corresponding owner instance
	//			a) try by EntityUniqueKey
	if ( collectionType.getLHSPropertyName() != null ) {
		final Object owner = getEntity(
				new EntityUniqueKey(
						ownerPersister.getEntityName(),
						collectionType.getLHSPropertyName(),
						key,
						collectionPersister.getKeyType(),
						ownerPersister.getEntityMode(),
						session.getFactory()
				)
		);
		if ( owner != null ) {
			return owner;
		}

		//		b) try by EntityKey, which means we need to resolve owner-key -> collection-key
		//			IMPL NOTE : yes if we get here this impl is very non-performant, but PersistenceContext
		//					was never designed to handle this case; adding that capability for real means splitting
		//					the notions of:
		//						1) collection key
		//						2) collection owner key
		// 					these 2 are not always the same (same is true in the case of ToOne associations with
		// 					property-ref).  That would require changes to (at least) CollectionEntry and quite
		//					probably changes to how the sql for collection initializers are generated
		//
		//			We could also possibly see if the referenced property is a natural id since we already have caching
		//			in place of natural id snapshots.  BUt really its better to just do it the right way ^^ if we start
		// 			going that route
		final Serializable ownerId = ownerPersister.getIdByUniqueKey( key, collectionType.getLHSPropertyName(), session );
		return getEntity( session.generateEntityKey( ownerId, ownerPersister ) );
	}

	// as a last resort this is what the old code did...
	return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) );
}
 
Example 12
Project: lams   File: DefaultMergeEventListener.java   View Source Code Vote up 4 votes
protected void entityIsDetached(MergeEvent event, Map copyCache) {

		LOG.trace( "Merging detached instance" );

		final Object entity = event.getEntity();
		final EventSource source = event.getSession();

		final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );
		final String entityName = persister.getEntityName();

		Serializable id = event.getRequestedId();
		if ( id == null ) {
			id = persister.getIdentifier( entity, source );
		}
		else {
			// check that entity id = requestedId
			Serializable entityId = persister.getIdentifier( entity, source );
			if ( !persister.getIdentifierType().isEqual( id, entityId, source.getFactory() ) ) {
				throw new HibernateException( "merge requested with id not matching id of passed entity" );
			}
		}

		String previousFetchProfile = source.getFetchProfile();
		source.setFetchProfile( "merge" );
		//we must clone embedded composite identifiers, or
		//we will get back the same instance that we pass in
		final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType()
				.deepCopy( id, source.getFactory() );
		final Object result = source.get( entityName, clonedIdentifier );
		source.setFetchProfile( previousFetchProfile );

		if ( result == null ) {
			//TODO: we should throw an exception if we really *know* for sure
			//      that this is a detached instance, rather than just assuming
			//throw new StaleObjectStateException(entityName, id);

			// we got here because we assumed that an instance
			// with an assigned id was detached, when it was
			// really persistent
			entityIsTransient( event, copyCache );
		}
		else {
			( (MergeContext) copyCache ).put( entity, result, true ); //before cascade!

			final Object target = source.getPersistenceContext().unproxy( result );
			if ( target == entity ) {
				throw new AssertionFailure( "entity was not detached" );
			}
			else if ( !source.getEntityName( target ).equals( entityName ) ) {
				throw new WrongClassException(
						"class of the given object did not match class of persistent copy",
						event.getRequestedId(),
						entityName
				);
			}
			else if ( isVersionChanged( entity, source, persister, target ) ) {
				if ( source.getFactory().getStatistics().isStatisticsEnabled() ) {
					source.getFactory().getStatisticsImplementor()
							.optimisticFailure( entityName );
				}
				throw new StaleObjectStateException( entityName, id );
			}

			// cascade first, so that all unsaved objects get their
			// copy created before we actually copy
			cascadeOnMerge( source, persister, entity, copyCache );
			copyValues( persister, entity, target, source, copyCache );

			//copyValues works by reflection, so explicitly mark the entity instance dirty
			markInterceptorDirty( entity, target, persister );

			event.setResult( result );
		}

	}