org.hibernate.event.spi.EventSource Java Examples
The following examples show how to use
org.hibernate.event.spi.EventSource.
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: Cascade.java From lams with GNU General Public License v2.0 | 6 votes |
/** * 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 #2
Source File: AbstractFlushingEventListener.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Execute all SQL (and second-level cache updates) in a special order so that foreign-key constraints cannot * be violated: <ol> * <li> Inserts, in the order they were performed * <li> Updates * <li> Deletion of collection elements * <li> Insertion of collection elements * <li> Deletes, in the order they were performed * </ol> * * @param session The session being flushed */ protected void performExecutions(EventSource session) { LOG.trace( "Executing flush" ); // IMPL NOTE : here we alter the flushing flag of the persistence context to allow // during-flush callbacks more leniency in regards to initializing proxies and // lazy collections during their processing. // For more information, see HHH-2763 try { session.getJdbcCoordinator().flushBeginning(); session.getPersistenceContext().setFlushing( true ); // we need to lock the collection caches before executing entity inserts/updates in order to // account for bi-directional associations session.getActionQueue().prepareActions(); session.getActionQueue().executeActions(); } finally { session.getPersistenceContext().setFlushing( false ); session.getJdbcCoordinator().flushEnding(); } }
Example #3
Source File: AbstractFlushingEventListener.java From lams with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings( value = {"unchecked"} ) private void logFlushResults(FlushEvent event) { if ( !LOG.isDebugEnabled() ) { return; } final EventSource session = event.getSession(); final PersistenceContext persistenceContext = session.getPersistenceContext(); LOG.debugf( "Flushed: %s insertions, %s updates, %s deletions to %s objects", session.getActionQueue().numberOfInsertions(), session.getActionQueue().numberOfUpdates(), session.getActionQueue().numberOfDeletions(), persistenceContext.getNumberOfManagedEntities() ); LOG.debugf( "Flushed: %s (re)creations, %s updates, %s removals to %s collections", session.getActionQueue().numberOfCollectionCreations(), session.getActionQueue().numberOfCollectionUpdates(), session.getActionQueue().numberOfCollectionRemovals(), persistenceContext.getCollectionEntries().size() ); new EntityPrinter( session.getFactory() ).toString( persistenceContext.getEntitiesByKey().entrySet() ); }
Example #4
Source File: DefaultDeleteEventListener.java From lams with GNU General Public License v2.0 | 6 votes |
/** * We encountered a delete request on a transient instance. * <p/> * This is a deviation from historical Hibernate (pre-3.2) behavior to * align with the JPA spec, which states that transient entities can be * passed to remove operation in which case cascades still need to be * performed. * * @param session The session which is the source of the event * @param entity The entity being delete processed * @param cascadeDeleteEnabled Is cascading of deletes enabled * @param persister The entity persister * @param transientEntities A cache of already visited transient entities * (to avoid infinite recursion). */ protected void deleteTransientEntity( EventSource session, Object entity, boolean cascadeDeleteEnabled, EntityPersister persister, Set transientEntities) { LOG.handlingTransientEntity(); if ( transientEntities.contains( entity ) ) { LOG.trace( "Already handled transient entity; skipping" ); return; } transientEntities.add( entity ); cascadeBeforeDelete( session, persister, entity, null, transientEntities ); cascadeAfterDelete( session, persister, entity, transientEntities ); }
Example #5
Source File: DefaultPersistEventListener.java From lams with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings({"unchecked"}) private void entityIsDeleted(PersistEvent event, Map createCache) { final EventSource source = event.getSession(); final Object entity = source.getPersistenceContext().unproxy( event.getObject() ); final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity ); LOG.tracef( "un-scheduling entity deletion [%s]", MessageHelper.infoString( persister, persister.getIdentifier( entity, source ), source.getFactory() ) ); if ( createCache.put( entity, entity ) == null ) { justCascade( createCache, source, entity, persister ); } }
Example #6
Source File: DefaultReactiveLoadEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
private CompletionStage<Object> doOnLoad( final EntityPersister persister, final LoadEvent event, final LoadEventListener.LoadType loadType) { final EventSource session = event.getSession(); final EntityKey keyToLoad = session.generateEntityKey( event.getEntityId(), persister ); if ( loadType.isNakedEntityReturned() ) { //do not return a proxy! //(this option indicates we are initializing a proxy) return load( event, persister, keyToLoad, loadType ); } //return a proxy if appropriate else if ( event.getLockMode() == LockMode.NONE ) { return proxyOrLoad( event, persister, keyToLoad, loadType ); } else { return lockAndLoad( event, persister, keyToLoad, loadType, session ); } }
Example #7
Source File: DefaultMergeEventListener.java From lams with GNU General Public License v2.0 | 6 votes |
private void saveTransientEntity( Object entity, String entityName, Serializable requestedId, EventSource source, Map copyCache) { //this bit is only *really* absolutely necessary for handling //requestedId, but is also good if we merge multiple object //graphs, since it helps ensure uniqueness if ( requestedId == null ) { saveWithGeneratedId( entity, entityName, copyCache, source, false ); } else { saveWithRequestedId( entity, requestedId, entityName, copyCache, source ); } }
Example #8
Source File: DefaultReactiveLoadEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
/** * Performs the load of an entity. * * @param event The initiating load request event * @param persister The persister corresponding to the entity to be loaded * @param keyToLoad The key of the entity to be loaded * @param options The defined load options * * @return The loaded entity. */ private CompletionStage<Object> load( LoadEvent event, EntityPersister persister, EntityKey keyToLoad, LoadType options) { final EventSource session = event.getSession(); if ( event.getInstanceToLoad() != null ) { if ( session.getPersistenceContextInternal().getEntry( event.getInstanceToLoad() ) != null ) { throw new PersistentObjectException( "attempted to load into an instance that was already associated with the session: " + MessageHelper.infoString( persister, event.getEntityId(), session.getFactory() ) ); } persister.setIdentifier( event.getInstanceToLoad(), event.getEntityId(), session ); } return doLoad( event, persister, keyToLoad, options ) .thenApply( optional -> { boolean isOptionalInstance = event.getInstanceToLoad() != null; if ( optional==null && ( !options.isAllowNulls() || isOptionalInstance ) ) { throwEntityNotFound( session, event.getEntityClassName(), event.getEntityId() ); } else if ( isOptionalInstance && optional != event.getInstanceToLoad() ) { throw new NonUniqueObjectException( event.getEntityId(), event.getEntityClassName() ); } return optional; } ); }
Example #9
Source File: AbstractReactiveFlushingEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
protected CompletionStage<Void> performExecutions(EventSource session) { LOG.trace( "Executing flush" ); // IMPL NOTE : here we alter the flushing flag of the persistence context to allow // during-flush callbacks more leniency in regards to initializing proxies and // lazy collections during their processing. // For more information, see HHH-2763 return CompletionStages.nullFuture() .thenCompose(v -> { session.getJdbcCoordinator().flushBeginning(); session.getPersistenceContext().setFlushing( true ); // we need to lock the collection caches before executing entity inserts/updates in order to // account for bi-directional associations actionQueue( session ).prepareActions(); return actionQueue( session ).executeActions(); } ) .whenComplete( (v, x) -> { session.getPersistenceContext().setFlushing( false ); session.getJdbcCoordinator().flushEnding(); } ); }
Example #10
Source File: AbstractSaveEventListener.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Prepares the save call using the given requested id. * * @param entity The entity to be saved. * @param requestedId The id to which to associate the entity. * @param entityName The name of the entity being saved. * @param anything Generally cascade-specific information. * @param source The session which is the source of this save event. * * @return The id used to save the entity. */ protected Serializable saveWithRequestedId( Object entity, Serializable requestedId, String entityName, Object anything, EventSource source) { callbackRegistry.preCreate( entity ); return performSave( entity, requestedId, source.getEntityPersister( entityName, entity ), false, anything, source, true ); }
Example #11
Source File: IteratorImpl.java From lams with GNU General Public License v2.0 | 6 votes |
public IteratorImpl( ResultSet rs, PreparedStatement ps, EventSource sess, boolean readOnly, Type[] types, String[][] columnNames, HolderInstantiator holderInstantiator) throws HibernateException, SQLException { this.rs = rs; this.ps = ps; this.session = sess; this.readOnly = readOnly; this.types = types; this.names = columnNames; this.holderInstantiator = holderInstantiator; single = types.length == 1; postNext(); }
Example #12
Source File: DefaultReactiveFlushEntityEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
private boolean wrapCollections( EventSource session, EntityPersister persister, Type[] types, Object[] values ) { if ( persister.hasCollections() ) { // wrap up any new collections directly referenced by the object // or its components // NOTE: we need to do the wrap here even if its not "dirty", // because collections need wrapping but changes to _them_ // don't dirty the container. Also, for versioned data, we // need to wrap before calling searchForDirtyCollections WrapVisitor visitor = new WrapVisitor( session ); // substitutes into values by side-effect visitor.processEntityPropertyValues( values, types ); return visitor.isSubstitutionRequired(); } else { return false; } }
Example #13
Source File: DefaultReactiveLockEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
private void cascadeOnLock(LockEvent event, EntityPersister persister, Object entity) { EventSource source = event.getSession(); final PersistenceContext persistenceContext = source.getPersistenceContextInternal(); persistenceContext.incrementCascadeLevel(); try { new Cascade( CascadingActions.LOCK, CascadePoint.AFTER_LOCK, persister, entity, event.getLockOptions(), source ).cascade(); } finally { persistenceContext.decrementCascadeLevel(); } }
Example #14
Source File: CascadingActions.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public Iterator getCascadableChildrenIterator( EventSource session, CollectionType collectionType, Object collection) { // lock doesn't cascade to uninitialized collections return getLoadedElementsIterator( session, collectionType, collection ); }
Example #15
Source File: CascadingActions.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void cascade( EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) { LOG.tracev( "Cascading to delete: {0}", entityName ); session.delete( entityName, child, isCascadeDeleteEnabled, (Set) anything ); }
Example #16
Source File: CascadingActions.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void cascade( EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { LOG.tracev( "Cascading to evict: {0}", entityName ); session.evict( child ); }
Example #17
Source File: DefaultMergeEventListener.java From lams with GNU General Public License v2.0 | 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 #18
Source File: CascadingActions.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void cascade( EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { LOG.tracev( "Cascading to replicate: {0}", entityName ); session.replicate( entityName, child, (ReplicationMode) anything ); }
Example #19
Source File: HQLQueryPlan.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Coordinates the efforts to perform an iterate across all the included query translators. * * @param queryParameters The query parameters * @param session The session * * @return The query result iterator * * @throws HibernateException Indicates a problem performing the query */ @SuppressWarnings("unchecked") public Iterator performIterate( QueryParameters queryParameters, EventSource session) throws HibernateException { if ( traceEnabled ) { LOG.tracev( "Iterate: {0}", getSourceQuery() ); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length == 0 ) { return Collections.emptyIterator(); } final boolean many = translators.length > 1; Iterator[] results = null; if ( many ) { results = new Iterator[translators.length]; } Iterator result = null; for ( int i = 0; i < translators.length; i++ ) { result = translators[i].iterate( queryParameters, session ); if ( many ) { results[i] = result; } } return many ? new JoinedIterator( results ) : result; }
Example #20
Source File: DefaultLoadEventListener.java From lams with GNU General Public License v2.0 | 5 votes |
private Iterable<PostLoadEventListener> postLoadEventListeners(EventSource session) { return session .getFactory() .getServiceRegistry() .getService( EventListenerRegistry.class ) .getEventListenerGroup( EventType.POST_LOAD ) .listeners(); }
Example #21
Source File: OptimisticLockingStrategy.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) { if ( !lockable.isVersioned() ) { throw new OptimisticLockException( object, "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } final EntityEntry entry = session.getPersistenceContext().getEntry( object ); // Register the EntityVerifyVersionProcess action to run just prior to transaction commit. ( (EventSource) session ).getActionQueue().registerProcess( new EntityVerifyVersionProcess( object, entry ) ); }
Example #22
Source File: AbstractReactiveFlushingEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
/** * 1. detect any dirty entities * 2. schedule any entity updates * 3. search out any reachable collections */ private int flushEntities(final FlushEvent event, final PersistenceContext persistenceContext) throws HibernateException { LOG.trace( "Flushing entities and processing referenced collections" ); final EventSource source = event.getSession(); final Iterable<FlushEntityEventListener> flushListeners = source.getFactory().getServiceRegistry() .getService( EventListenerRegistry.class ) .getEventListenerGroup( EventType.FLUSH_ENTITY ) .listeners(); // Among other things, updateReachables() will recursively load all // collections that are moving roles. This might cause entities to // be loaded. // So this needs to be safe from concurrent modification problems. final Map.Entry<Object,EntityEntry>[] entityEntries = persistenceContext.reentrantSafeEntityEntries(); final int count = entityEntries.length; for ( Map.Entry<Object,EntityEntry> me : entityEntries ) { // Update the status of the object and if necessary, schedule an update EntityEntry entry = me.getValue(); Status status = entry.getStatus(); if ( status != Status.LOADING && status != Status.GONE ) { final FlushEntityEvent entityEvent = new FlushEntityEvent( source, me.getKey(), entry ); for ( FlushEntityEventListener listener : flushListeners ) { listener.onFlushEntity( entityEvent ); } } } source.getActionQueue().sortActions(); return count; }
Example #23
Source File: AbstractReactiveFlushingEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
/** * Coordinates the processing necessary to get things ready for executions * as db calls by preping the session caches and moving the appropriate * entities and collections to their respective execution queues. * * @param event The flush event. * @throws HibernateException Error flushing caches to execution queues. */ protected CompletionStage<Void> flushEverythingToExecutions(FlushEvent event) throws HibernateException { LOG.trace( "Flushing session" ); EventSource session = event.getSession(); final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); session.getInterceptor().preFlush( persistenceContext.managedEntitiesIterator() ); CompletionStage<Void> cascades = prepareEntityFlushes(session, persistenceContext); // we could move this inside if we wanted to // tolerate collection initializations during // collection dirty checking: prepareCollectionFlushes( persistenceContext ); // now, any collections that are initialized // inside this block do not get updated - they // are ignored until the next flush return cascades.thenAccept( v -> { persistenceContext.setFlushing(true); try { int entityCount = flushEntities(event, persistenceContext); int collectionCount = flushCollections(session, persistenceContext); event.setNumberOfEntitiesProcessed(entityCount); event.setNumberOfCollectionsProcessed(collectionCount); } finally { persistenceContext.setFlushing(false); } }); //some statistics // logFlushResults( event ); }
Example #24
Source File: ReattachVisitor.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Schedules a collection for deletion. * * @param role The persister representing the collection to be removed. * @param collectionKey The collection key (differs from owner-id in the case of property-refs). * @param source The session from which the request originated. * * @throws HibernateException */ void removeCollection(CollectionPersister role, Serializable collectionKey, EventSource source) throws HibernateException { if ( LOG.isTraceEnabled() ) { LOG.tracev( "Collection dereferenced while transient {0}", MessageHelper.collectionInfoString( role, ownerIdentifier, source.getFactory() ) ); } source.getActionQueue().addAction( new CollectionRemoveAction( owner, role, collectionKey, false, source ) ); }
Example #25
Source File: DefaultFlushEntityEventListener.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Flushes a single entity's state to the database, by scheduling * an update action, if necessary */ public void onFlushEntity(FlushEntityEvent event) throws HibernateException { final Object entity = event.getEntity(); final EntityEntry entry = event.getEntityEntry(); final EventSource session = event.getSession(); final EntityPersister persister = entry.getPersister(); final Status status = entry.getStatus(); final Type[] types = persister.getPropertyTypes(); final boolean mightBeDirty = entry.requiresDirtyCheck( entity ); final Object[] values = getValues( entity, entry, mightBeDirty, session ); event.setPropertyValues( values ); //TODO: avoid this for non-new instances where mightBeDirty==false boolean substitute = wrapCollections( session, persister, types, values ); if ( isUpdateNecessary( event, mightBeDirty ) ) { substitute = scheduleUpdate( event ) || substitute; } if ( status != Status.DELETED ) { // now update the object .. has to be outside the main if block above (because of collections) if ( substitute ) { persister.setPropertyValues( entity, values ); } // Search for collections by reachability, updating their role. // We don't want to touch collections reachable from a deleted object if ( persister.hasCollections() ) { new FlushVisitor( session, entity ).processEntityPropertyValues( values, types ); } } }
Example #26
Source File: CascadingActions.java From lams with GNU General Public License v2.0 | 5 votes |
@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 #27
Source File: CascadingActions.java From lams with GNU General Public License v2.0 | 5 votes |
private boolean isInManagedState(Object child, EventSource session) { EntityEntry entry = session.getPersistenceContext().getEntry( child ); return entry != null && ( entry.getStatus() == Status.MANAGED || entry.getStatus() == Status.READ_ONLY || entry.getStatus() == Status.SAVING ); }
Example #28
Source File: DefaultReactiveFlushEntityEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
/** * Flushes a single entity's state to the database, by scheduling * an update action, if necessary */ public void onFlushEntity(FlushEntityEvent event) throws HibernateException { final Object entity = event.getEntity(); final EntityEntry entry = event.getEntityEntry(); final EventSource session = event.getSession(); final EntityPersister persister = entry.getPersister(); final Status status = entry.getStatus(); final Type[] types = persister.getPropertyTypes(); final boolean mightBeDirty = entry.requiresDirtyCheck( entity ); final Object[] values = getValues( entity, entry, mightBeDirty, session ); event.setPropertyValues( values ); //TODO: avoid this for non-new instances where mightBeDirty==false boolean substitute = wrapCollections( session, persister, types, values ); if ( isUpdateNecessary( event, mightBeDirty ) ) { substitute = scheduleUpdate( event ) || substitute; } if ( status != Status.DELETED ) { // now update the object .. has to be outside the main if block above (because of collections) if ( substitute ) { persister.setPropertyValues( entity, values ); } // Search for collections by reachability, updating their role. // We don't want to touch collections reachable from a deleted object if ( persister.hasCollections() ) { new FlushVisitor( session, entity ).processEntityPropertyValues( values, types ); } } }
Example #29
Source File: Cascade.java From lams with GNU General Public License v2.0 | 5 votes |
/** * 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 #30
Source File: EntityCopyAllowedLoggedObserver.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void entityCopyDetected( Object managedEntity, Object mergeEntity1, Object mergeEntity2, EventSource session) { final String entityName = session.getEntityName( managedEntity ); LOG.trace( String.format( "More than one representation of the same persistent entity being merged for: %s", MessageHelper.infoString( entityName, session.getIdentifier( managedEntity ) ) ) ); Set<Object> detachedEntitiesForManaged = null; if ( managedToMergeEntitiesXref == null ) { // This is the first time multiple representations have been found; // instantiate managedToMergeEntitiesXref. managedToMergeEntitiesXref = new IdentityHashMap<Object, Set<Object>>(); } else { // Get any existing representations that have already been found. detachedEntitiesForManaged = managedToMergeEntitiesXref.get( managedEntity ); } if ( detachedEntitiesForManaged == null ) { // There were no existing representations for this particular managed entity; detachedEntitiesForManaged = new IdentitySet(); managedToMergeEntitiesXref.put( managedEntity, detachedEntitiesForManaged ); incrementEntityNameCount( entityName ); } // Now add the detached representation for the managed entity; detachedEntitiesForManaged.add( mergeEntity1 ); detachedEntitiesForManaged.add( mergeEntity2 ); }