Java Code Examples for org.hibernate.engine.spi.EntityEntry#getId()
The following examples show how to use
org.hibernate.engine.spi.EntityEntry#getId() .
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: SessionImpl.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public LockMode getCurrentLockMode(Object object) throws HibernateException { checkOpen(); checkTransactionSynchStatus(); if ( object == null ) { throw new NullPointerException( "null object passed to getCurrentLockMode()" ); } if ( object instanceof HibernateProxy ) { object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation( this ); if ( object == null ) { return LockMode.NONE; } } EntityEntry e = persistenceContext.getEntry( object ); if ( e == null ) { throw new TransientObjectException( "Given object not associated with the session" ); } if ( e.getStatus() != Status.MANAGED ) { throw new ObjectDeletedException( "The given object was deleted", e.getId(), e.getPersister().getEntityName() ); } return e.getLockMode(); }
Example 2
Source File: SessionImpl.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public void forceFlush(EntityEntry entityEntry) throws HibernateException { if ( log.isDebugEnabled() ) { log.debugf( "Flushing to force deletion of re-saved object: %s", MessageHelper.infoString( entityEntry.getPersister(), entityEntry.getId(), getFactory() ) ); } if ( persistenceContext.getCascadeLevel() > 0 ) { throw new ObjectDeletedException( "deleted object would be re-saved by cascade (remove deleted object from associations)", entityEntry.getId(), entityEntry.getPersister().getEntityName() ); } checkOpenOrWaitingForAutoClose(); doFlush(); }
Example 3
Source File: SessionImpl.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public Serializable getIdentifier(Object object) throws HibernateException { checkOpen(); checkTransactionSynchStatus(); if ( object instanceof HibernateProxy ) { LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); if ( li.getSession() != this ) { throw new TransientObjectException( "The proxy was not associated with this session" ); } return li.getIdentifier(); } else { EntityEntry entry = persistenceContext.getEntry( object ); if ( entry == null ) { throw new TransientObjectException( "The instance was not associated with this session" ); } return entry.getId(); } }
Example 4
Source File: EntityAction.java From lams with GNU General Public License v2.0 | 6 votes |
/** * entity id accessor * * @return The entity id */ public final Serializable getId() { if ( id instanceof DelayedPostInsertIdentifier ) { final EntityEntry entry = session.getPersistenceContext().getEntry( instance ); if ( entry == null ) { if ( LOG.isDebugEnabled() ) { LOG.debugf( "Skipping action - the persistence context does not contain any entry for the entity [%s]. This may occur if an entity is created and then deleted in the same transaction/flush.", instance ); } // If an Entity is created and then deleted in the same Transaction, when Action#postDelete() calls this method the persistence context // does not contain anymore an entry. return null; } final Serializable eeId = entry.getId(); return eeId instanceof DelayedPostInsertIdentifier ? null : eeId; } return id; }
Example 5
Source File: MessageHelper.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Generate an info message string relating to a particular managed * collection. Attempts to intelligently handle property-refs issues * where the collection key is not the same as the owner key. * * @param persister The persister for the collection * @param collection The collection itself * @param collectionKey The collection key * @param session The session * @return An info string, in the form [Foo.bars#1] */ public static String collectionInfoString( CollectionPersister persister, PersistentCollection collection, Serializable collectionKey, SharedSessionContractImplementor session ) { StringBuilder s = new StringBuilder(); s.append( '[' ); if ( persister == null ) { s.append( "<unreferenced>" ); } else { s.append( persister.getRole() ); s.append( '#' ); Type ownerIdentifierType = persister.getOwnerEntityPersister() .getIdentifierType(); Serializable ownerKey; // TODO: Is it redundant to attempt to use the collectionKey, // or is always using the owner id sufficient? if ( collectionKey.getClass().isAssignableFrom( ownerIdentifierType.getReturnedClass() ) ) { ownerKey = collectionKey; } else { Object collectionOwner = collection == null ? null : collection.getOwner(); EntityEntry entry = collectionOwner == null ? null : session.getPersistenceContext().getEntry(collectionOwner); ownerKey = entry == null ? null : entry.getId(); } s.append( ownerIdentifierType.toLoggableString( ownerKey, session.getFactory() ) ); } s.append( ']' ); return s.toString(); }
Example 6
Source File: AbstractEntityTuplizer.java From lams with GNU General Public License v2.0 | 5 votes |
private static Serializable determineEntityId( Object entity, AssociationType associationType, SharedSessionContractImplementor session, SessionFactoryImplementor sessionFactory) { if ( entity == null ) { return null; } if ( HibernateProxy.class.isInstance( entity ) ) { // entity is a proxy, so we know it is not transient; just return ID from proxy return ( (HibernateProxy) entity ).getHibernateLazyInitializer().getIdentifier(); } if ( session != null ) { final EntityEntry pcEntry = session.getPersistenceContext().getEntry( entity ); if ( pcEntry != null ) { // entity managed; return ID. return pcEntry.getId(); } } final EntityPersister persister = resolveEntityPersister( entity, associationType, session, sessionFactory ); return persister.getIdentifier( entity, session ); }
Example 7
Source File: PersistenceUnitUtilImpl.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public Object getIdentifier(Object entity) { if ( entity == null ) { throw new IllegalArgumentException( "Passed entity cannot be null" ); } if ( entity instanceof HibernateProxy ) { return ((HibernateProxy) entity).getHibernateLazyInitializer().getIdentifier(); } else if ( entity instanceof ManagedEntity ) { EntityEntry entityEntry = ((ManagedEntity) entity).$$_hibernate_getEntityEntry(); if ( entityEntry != null ) { return entityEntry.getId(); } else { // HHH-11426 - best effort to deal with the case of detached entities log.debug( "javax.persistence.PersistenceUnitUtil.getIdentifier may not be able to read identifier of a detached entity" ); return getIdentifierFromPersister( entity ); } } else { log.debugf( "javax.persistence.PersistenceUnitUtil.getIdentifier is only intended to work with enhanced entities " + "(although Hibernate also adapts this support to its proxies); " + "however the passed entity was not enhanced (nor a proxy).. may not be able to read identifier" ); return getIdentifierFromPersister( entity ); } }
Example 8
Source File: SessionImpl.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Get the id value for an object that is actually associated with the session. This * is a bit stricter than getEntityIdentifierIfNotUnsaved(). */ @Override public Serializable getContextEntityIdentifier(Object object) { checkOpenOrWaitingForAutoClose(); if ( object instanceof HibernateProxy ) { return getProxyIdentifier( object ); } else { EntityEntry entry = persistenceContext.getEntry( object ); return entry != null ? entry.getId() : null; } }
Example 9
Source File: DefaultReactiveLockEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 4 votes |
/** * Performs a pessimistic lock upgrade on a given entity, if needed. * * @param object The entity for which to upgrade the lock. * @param entry The entity's EntityEntry instance. * @param lockOptions contains the requested lock mode. * @param source The session which is the source of the event being processed. */ protected CompletionStage<Void> upgradeLock(Object object, EntityEntry entry, LockOptions lockOptions, EventSource source) { LockMode requestedLockMode = lockOptions.getLockMode(); if ( requestedLockMode.greaterThan( entry.getLockMode() ) ) { // The user requested a "greater" (i.e. more restrictive) form of // pessimistic lock if ( entry.getStatus() != Status.MANAGED ) { throw new ObjectDeletedException( "attempted to lock a deleted instance", entry.getId(), entry.getPersister().getEntityName() ); } final EntityPersister persister = entry.getPersister(); if ( log.isTraceEnabled() ) { log.tracev( "Locking {0} in mode: {1}", MessageHelper.infoString( persister, entry.getId(), source.getFactory() ), requestedLockMode ); } final boolean cachingEnabled = persister.canWriteToCache(); final SoftLock lock; final Object ck; if ( cachingEnabled ) { EntityDataAccess cache = persister.getCacheAccessStrategy(); ck = cache.generateCacheKey( entry.getId(), persister, source.getFactory(), source.getTenantIdentifier() ); lock = cache.lockItem( source, ck, entry.getVersion() ); } else { lock = null; ck = null; } return ((ReactiveEntityPersister) persister).lockReactive( entry.getId(), entry.getVersion(), object, lockOptions, source ).thenAccept( v -> entry.setLockMode(requestedLockMode) ) .whenComplete( (r, e) -> { // the database now holds a lock + the object is flushed from the cache, // so release the soft lock if ( cachingEnabled ) { persister.getCacheAccessStrategy().unlockItem( source, ck, lock ); } } ); } else { return CompletionStages.nullFuture(); } }
Example 10
Source File: Collections.java From lams with GNU General Public License v2.0 | 4 votes |
private static void processDereferencedCollection(PersistentCollection coll, SessionImplementor session) { final PersistenceContext persistenceContext = session.getPersistenceContext(); final CollectionEntry entry = persistenceContext.getCollectionEntry( coll ); final CollectionPersister loadedPersister = entry.getLoadedPersister(); if ( loadedPersister != null && LOG.isDebugEnabled() ) { LOG.debugf( "Collection dereferenced: %s", MessageHelper.collectionInfoString( loadedPersister, coll, entry.getLoadedKey(), session ) ); } // do a check final boolean hasOrphanDelete = loadedPersister != null && loadedPersister.hasOrphanDelete(); if ( hasOrphanDelete ) { Serializable ownerId = loadedPersister.getOwnerEntityPersister().getIdentifier( coll.getOwner(), session ); if ( ownerId == null ) { // the owning entity may have been deleted and its identifier unset due to // identifier-rollback; in which case, try to look up its identifier from // the persistence context if ( session.getFactory().getSessionFactoryOptions().isIdentifierRollbackEnabled() ) { final EntityEntry ownerEntry = persistenceContext.getEntry( coll.getOwner() ); if ( ownerEntry != null ) { ownerId = ownerEntry.getId(); } } if ( ownerId == null ) { throw new AssertionFailure( "Unable to determine collection owner identifier for orphan-delete processing" ); } } final EntityKey key = session.generateEntityKey( ownerId, loadedPersister.getOwnerEntityPersister() ); final Object owner = persistenceContext.getEntity( key ); if ( owner == null ) { throw new AssertionFailure( "collection owner not associated with session: " + loadedPersister.getRole() ); } final EntityEntry e = persistenceContext.getEntry( owner ); //only collections belonging to deleted entities are allowed to be dereferenced in the case of orphan delete if ( e != null && e.getStatus() != Status.DELETED && e.getStatus() != Status.GONE ) { throw new HibernateException( "A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: " + loadedPersister.getRole() ); } } // do the work entry.setCurrentPersister( null ); entry.setCurrentKey( null ); prepareCollectionForUpdate( coll, entry, session.getFactory() ); }
Example 11
Source File: AbstractCollectionEvent.java From lams with GNU General Public License v2.0 | 4 votes |
protected static Serializable getOwnerIdOrNull( Object owner, EventSource source ) { EntityEntry ownerEntry = source.getPersistenceContext().getEntry( owner ); return ( ownerEntry == null ? null : ownerEntry.getId() ); }
Example 12
Source File: AbstractLockUpgradeEventListener.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Performs a pessimistic lock upgrade on a given entity, if needed. * * @param object The entity for which to upgrade the lock. * @param entry The entity's EntityEntry instance. * @param lockOptions contains the requested lock mode. * @param source The session which is the source of the event being processed. */ protected void upgradeLock(Object object, EntityEntry entry, LockOptions lockOptions, EventSource source) { LockMode requestedLockMode = lockOptions.getLockMode(); if ( requestedLockMode.greaterThan( entry.getLockMode() ) ) { // The user requested a "greater" (i.e. more restrictive) form of // pessimistic lock if ( entry.getStatus() != Status.MANAGED ) { throw new ObjectDeletedException( "attempted to lock a deleted instance", entry.getId(), entry.getPersister().getEntityName() ); } final EntityPersister persister = entry.getPersister(); if ( log.isTraceEnabled() ) { log.tracev( "Locking {0} in mode: {1}", MessageHelper.infoString( persister, entry.getId(), source.getFactory() ), requestedLockMode ); } final boolean cachingEnabled = persister.canWriteToCache(); SoftLock lock = null; Object ck = null; try { if ( cachingEnabled ) { EntityDataAccess cache = persister.getCacheAccessStrategy(); ck = cache.generateCacheKey( entry.getId(), persister, source.getFactory(), source.getTenantIdentifier() ); lock = cache.lockItem( source, ck, entry.getVersion() ); } if ( persister.isVersioned() && requestedLockMode == LockMode.FORCE ) { // todo : should we check the current isolation mode explicitly? Object nextVersion = persister.forceVersionIncrement( entry.getId(), entry.getVersion(), source ); entry.forceLocked( object, nextVersion ); } else { persister.lock( entry.getId(), entry.getVersion(), object, lockOptions, source ); } entry.setLockMode(requestedLockMode); } finally { // the database now holds a lock + the object is flushed from the cache, // so release the soft lock if ( cachingEnabled ) { persister.getCacheAccessStrategy().unlockItem( source, ck, lock ); } } } }
Example 13
Source File: DefaultDeleteEventListener.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Handle the given delete event. This is the cascaded form. * * @param event The delete event. * @param transientEntities The cache of entities already deleted * * @throws HibernateException */ public void onDelete(DeleteEvent event, Set transientEntities) throws HibernateException { final EventSource source = event.getSession(); final PersistenceContext persistenceContext = source.getPersistenceContext(); Object entity = persistenceContext.unproxyAndReassociate( event.getObject() ); EntityEntry entityEntry = persistenceContext.getEntry( entity ); final EntityPersister persister; final Serializable id; final Object version; if ( entityEntry == null ) { LOG.trace( "Entity was not persistent in delete processing" ); persister = source.getEntityPersister( event.getEntityName(), entity ); if ( ForeignKeys.isTransient( persister.getEntityName(), entity, null, source ) ) { deleteTransientEntity( source, entity, event.isCascadeDeleteEnabled(), persister, transientEntities ); // EARLY EXIT!!! return; } performDetachedEntityDeletionCheck( event ); id = persister.getIdentifier( entity, source ); if ( id == null ) { throw new TransientObjectException( "the detached instance passed to delete() had a null identifier" ); } final EntityKey key = source.generateEntityKey( id, persister ); persistenceContext.checkUniqueness( key, entity ); new OnUpdateVisitor( source, id, entity ).process( entity, persister ); version = persister.getVersion( entity ); entityEntry = persistenceContext.addEntity( entity, (persister.isMutable() ? Status.MANAGED : Status.READ_ONLY), persister.getPropertyValues( entity ), key, version, LockMode.NONE, true, persister, false ); } else { LOG.trace( "Deleting a persistent instance" ); if ( entityEntry.getStatus() == Status.DELETED || entityEntry.getStatus() == Status.GONE ) { LOG.trace( "Object was already deleted" ); return; } persister = entityEntry.getPersister(); id = entityEntry.getId(); version = entityEntry.getVersion(); } /*if ( !persister.isMutable() ) { throw new HibernateException( "attempted to delete an object of immutable class: " + MessageHelper.infoString(persister) ); }*/ if ( invokeDeleteLifecycle( source, entity, persister ) ) { return; } deleteEntity( source, entity, entityEntry, event.isCascadeDeleteEnabled(), event.isOrphanRemovalBeforeUpdates(), persister, transientEntities ); if ( source.getFactory().getSettings().isIdentifierRollbackEnabled() ) { persister.resetIdentifier( entity, id, version, source ); } }
Example 14
Source File: DefaultSaveOrUpdateEventListener.java From lams with GNU General Public License v2.0 | 4 votes |
protected Serializable entityIsPersistent(SaveOrUpdateEvent event) throws HibernateException { final boolean traceEnabled = LOG.isTraceEnabled(); if ( traceEnabled ) { LOG.trace( "Ignoring persistent instance" ); } EntityEntry entityEntry = event.getEntry(); if ( entityEntry == null ) { throw new AssertionFailure( "entity was transient or detached" ); } else { if ( entityEntry.getStatus() == Status.DELETED ) { throw new AssertionFailure( "entity was deleted" ); } final SessionFactoryImplementor factory = event.getSession().getFactory(); Serializable requestedId = event.getRequestedId(); Serializable savedId; if ( requestedId == null ) { savedId = entityEntry.getId(); } else { final boolean isEqual = !entityEntry.getPersister().getIdentifierType() .isEqual( requestedId, entityEntry.getId(), factory ); if ( isEqual ) { throw new PersistentObjectException( "object passed to save() was already persistent: " + MessageHelper.infoString( entityEntry.getPersister(), requestedId, factory ) ); } savedId = requestedId; } if ( traceEnabled ) { LOG.tracev( "Object already associated with session: {0}", MessageHelper.infoString( entityEntry.getPersister(), savedId, factory ) ); } return savedId; } }
Example 15
Source File: CollectionType.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Get the key value from the owning entity instance, usually the identifier, but might be some * other unique key, in the case of property-ref * * @param owner The collection owner * @param session The session from which the request is originating. * @return The collection owner's key */ public Serializable getKeyOfOwner(Object owner, SharedSessionContractImplementor session) { EntityEntry entityEntry = session.getPersistenceContext().getEntry( owner ); if ( entityEntry == null ) { // This just handles a particular case of component // projection, perhaps get rid of it and throw an exception return null; } if ( foreignKeyPropertyName == null ) { return entityEntry.getId(); } else { // TODO: at the point where we are resolving collection references, we don't // know if the uk value has been resolved (depends if it was earlier or // later in the mapping document) - now, we could try and use e.getStatus() // to decide to semiResolve(), trouble is that initializeEntity() reuses // the same array for resolved and hydrated values Object id; if ( entityEntry.getLoadedState() != null ) { id = entityEntry.getLoadedValue( foreignKeyPropertyName ); } else { id = entityEntry.getPersister().getPropertyValue( owner, foreignKeyPropertyName ); } // NOTE VERY HACKISH WORKAROUND!! // TODO: Fix this so it will work for non-POJO entity mode Type keyType = getPersister( session ).getKeyType(); Class returnedClass = keyType.getReturnedClass(); if ( !returnedClass.isInstance( id ) ) { id = keyType.semiResolve( entityEntry.getLoadedValue( foreignKeyPropertyName ), session, owner ); } return (Serializable) id; } }