下面列出了怎么用org.hibernate.event.spi.EventType的API类实例代码及写法,或者点击链接到github查看源代码。
public CompletionStage<Void> reactiveInitializeCollection(PersistentCollection collection, boolean writing) {
checkOpenOrWaitingForAutoClose();
pulseTransactionCoordinator();
InitializeCollectionEvent event = new InitializeCollectionEvent( collection, this );
return fire( event, EventType.INIT_COLLECTION,
(DefaultReactiveInitializeCollectionEventListener l) -> l::onReactiveInitializeCollection )
.handle( (v, e) -> {
delayedAfterCompletion();
if ( e instanceof MappingException ) {
throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage() ) );
}
else if ( e instanceof RuntimeException ) {
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
} );
}
private CompletionStage<Void> firePersist(IdentitySet copiedAlready, PersistEvent event) {
pulseTransactionCoordinator();
return fire(event, copiedAlready, EventType.PERSIST,
(ReactivePersistEventListener l) -> l::reactiveOnPersist)
.handle( (v, e) -> {
delayedAfterCompletion();
if (e instanceof MappingException) {
throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage() ) );
}
else if (e instanceof RuntimeException) {
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
});
}
private CompletionStage<Void> fireRemove(DeleteEvent event) {
pulseTransactionCoordinator();
return fire(event, EventType.DELETE,
(ReactiveDeleteEventListener l) -> l::reactiveOnDelete)
.handle( (v, e) -> {
delayedAfterCompletion();
if ( e instanceof ObjectDeletedException ) {
throw getExceptionConverter().convert( new IllegalArgumentException( e ) );
}
else if ( e instanceof MappingException ) {
throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) );
}
else if ( e instanceof RuntimeException ) {
//including HibernateException
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
});
}
private CompletionStage<Void> fireRemove(DeleteEvent event, IdentitySet transientEntities) {
pulseTransactionCoordinator();
return fire(event, transientEntities, EventType.DELETE,
(ReactiveDeleteEventListener l) -> l::reactiveOnDelete)
.handle( (v, e) -> {
delayedAfterCompletion();
if ( e instanceof ObjectDeletedException ) {
throw getExceptionConverter().convert( new IllegalArgumentException( e ) );
}
else if ( e instanceof MappingException ) {
throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) );
}
else if ( e instanceof RuntimeException ) {
//including HibernateException
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
});
}
@SuppressWarnings("unchecked")
private <T> CompletionStage<T> fireMerge(MergeEvent event) {
checkTransactionSynchStatus();
checkNoUnresolvedActionsBeforeOperation();
return fire(event, EventType.MERGE,
(ReactiveMergeEventListener l) -> l::reactiveOnMerge)
.handle( (v,e) -> {
checkNoUnresolvedActionsAfterOperation();
if (e instanceof ObjectDeletedException) {
throw getExceptionConverter().convert( new IllegalArgumentException( e ) );
}
else if (e instanceof MappingException) {
throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) );
}
else if (e instanceof RuntimeException) {
//including HibernateException
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnOrRethrow( e, (T) event.getResult() );
});
}
private CompletionStage<Void> fireMerge(MergeContext copiedAlready, MergeEvent event) {
pulseTransactionCoordinator();
return fire(event, copiedAlready, EventType.MERGE,
(ReactiveMergeEventListener l) -> l::reactiveOnMerge)
.handle( (v,e) -> {
delayedAfterCompletion();
if (e instanceof ObjectDeletedException) {
throw getExceptionConverter().convert( new IllegalArgumentException( e ) );
}
else if (e instanceof MappingException) {
throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) );
}
else if (e instanceof RuntimeException) {
//including HibernateException
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
});
}
private CompletionStage<Void> doFlush() {
checkTransactionNeededForUpdateOperation( "no transaction is in progress" );
pulseTransactionCoordinator();
if ( getPersistenceContextInternal().getCascadeLevel() > 0 ) {
throw new HibernateException( "Flush during cascade is dangerous" );
}
return fire(new FlushEvent( this ), EventType.FLUSH,
(ReactiveFlushEventListener l) -> l::reactiveOnFlush)
.handle( (v, e) -> {
delayedAfterCompletion();
if ( e instanceof RuntimeException ) {
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
} );
}
private void postInsert() {
if ( isDelayed ) {
getSession().getPersistenceContext().replaceDelayedEntityIdentityInsertKeys( delayedEntityKey, generatedId );
}
final EventListenerGroup<PostInsertEventListener> listenerGroup = listenerGroup( EventType.POST_INSERT );
if ( listenerGroup.isEmpty() ) {
return;
}
final PostInsertEvent event = new PostInsertEvent(
getInstance(),
generatedId,
getState(),
getPersister(),
eventSource()
);
for ( PostInsertEventListener listener : listenerGroup.listeners() ) {
listener.onPostInsert( event );
}
}
private void attachEventContextManagingListenersIfRequired(SessionFactoryServiceRegistry serviceRegistry) {
if ( ReactiveModeCheck.isReactiveRegistry( serviceRegistry ) ) {
CoreLogging.messageLogger(ReactiveIntegrator.class).info("HRX000001: Hibernate Reactive Preview");
EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
eventListenerRegistry.addDuplicationStrategy( ReplacementDuplicationStrategy.INSTANCE );
eventListenerRegistry.getEventListenerGroup( EventType.AUTO_FLUSH ).appendListener( new DefaultReactiveAutoFlushEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.FLUSH ).appendListener( new DefaultReactiveFlushEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.FLUSH_ENTITY ).appendListener( new DefaultReactiveFlushEntityEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.PERSIST ).appendListener( new DefaultReactivePersistEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.PERSIST_ONFLUSH ).appendListener( new DefaultReactivePersistOnFlushEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.MERGE ).appendListener( new DefaultReactiveMergeEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.DELETE ).appendListener( new DefaultReactiveDeleteEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.REFRESH ).appendListener( new DefaultReactiveRefreshEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.LOCK ).appendListener( new DefaultReactiveLockEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.LOAD ).appendListener( new DefaultReactiveLoadEventListener() );
eventListenerRegistry.getEventListenerGroup( EventType.INIT_COLLECTION ).appendListener( new DefaultReactiveInitializeCollectionEventListener() );
}
}
/**
* PostLoad cannot occur during initializeEntity, as that call occurs *before*
* the Set collections are added to the persistence context by Loader.
* Without the split, LazyInitializationExceptions can occur in the Entity's
* postLoad if it acts upon the collection.
*
* HHH-6043
*
* @param entity The entity
* @param session The Session
* @param postLoadEvent The (re-used) post-load event
*/
public static void postLoad(
final Object entity,
final SharedSessionContractImplementor session,
final PostLoadEvent postLoadEvent) {
if ( session.isEventSource() ) {
final PersistenceContext persistenceContext
= session.getPersistenceContext();
final EntityEntry entityEntry = persistenceContext.getEntry( entity );
postLoadEvent.setEntity( entity ).setId( entityEntry.getId() ).setPersister( entityEntry.getPersister() );
final EventListenerGroup<PostLoadEventListener> listenerGroup = session.getFactory()
.getServiceRegistry()
.getService( EventListenerRegistry.class )
.getEventListenerGroup( EventType.POST_LOAD );
for ( PostLoadEventListener listener : listenerGroup.listeners() ) {
listener.onPostLoad( postLoadEvent );
}
}
}
@Override
public boolean isDirty() throws HibernateException {
checkOpen();
checkTransactionSynchStatus();
log.debug( "Checking session dirtiness" );
if ( actionQueue.areInsertionsOrDeletionsQueued() ) {
log.debug( "Session dirty (scheduled updates and insertions)" );
return true;
}
DirtyCheckEvent event = new DirtyCheckEvent( this );
for ( DirtyCheckEventListener listener : listeners( EventType.DIRTY_CHECK ) ) {
listener.onDirtyCheck( event );
}
delayedAfterCompletion();
return event.isDirty();
}
private void prepareEventListeners(MetadataImplementor metadata) {
final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
final ConfigurationService cfgService = serviceRegistry.getService( ConfigurationService.class );
final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
eventListenerRegistry.prepare( metadata );
for ( Map.Entry entry : ( (Map<?, ?>) cfgService.getSettings() ).entrySet() ) {
if ( !String.class.isInstance( entry.getKey() ) ) {
continue;
}
final String propertyName = (String) entry.getKey();
if ( !propertyName.startsWith( org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX ) ) {
continue;
}
final String eventTypeName = propertyName.substring(
org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX.length() + 1
);
final EventType eventType = EventType.resolveEventTypeByName( eventTypeName );
final EventListenerGroup eventListenerGroup = eventListenerRegistry.getEventListenerGroup( eventType );
for ( String listenerImpl : ( (String) entry.getValue() ).split( " ," ) ) {
eventListenerGroup.appendListener( instantiate( listenerImpl, classLoaderService ) );
}
}
}
@SuppressWarnings("unchecked")
protected <T> void appendListeners(final EventListenerRegistry listenerRegistry,
final EventType<T> eventType, final Map<String, Object> listeners) {
Object listener = listeners.get(eventType.eventName());
if (listener != null) {
if(shouldOverrideListeners(eventType, listener)) {
// since ClosureEventTriggeringInterceptor extends DefaultSaveOrUpdateEventListener we want to override instead of append the listener here
// to avoid there being 2 implementations which would impact performance too
listenerRegistry.setListeners(eventType, (T) listener);
}
else {
listenerRegistry.appendListeners(eventType, (T)listener);
}
}
}
public EventListenerGroupImpl(EventType<T> eventType, EventListenerRegistryImpl listenerRegistry) {
this.eventType = eventType;
this.listenerRegistry = listenerRegistry;
duplicationStrategies.add(
// At minimum make sure we do not register the same exact listener class multiple times.
new DuplicationStrategy() {
@Override
public boolean areMatch(Object listener, Object original) {
return listener.getClass().equals( original.getClass() );
}
@Override
public Action getAction() {
return Action.ERROR;
}
}
);
}
private void postUpdate() {
final EventListenerGroup<PostUpdateEventListener> listenerGroup = listenerGroup( EventType.POST_UPDATE );
if ( listenerGroup.isEmpty() ) {
return;
}
final PostUpdateEvent event = new PostUpdateEvent(
getInstance(),
getId(),
state,
previousState,
dirtyFields,
getPersister(),
eventSource()
);
for ( PostUpdateEventListener listener : listenerGroup.listeners() ) {
listener.onPostUpdate( event );
}
}
private <T> void prepareListeners(EventType<T> type, T defaultListener, EventListenerGroupImpl[] listenerArray) {
final EventListenerGroupImpl<T> listenerGroup;
if ( type == EventType.POST_COMMIT_DELETE
|| type == EventType.POST_COMMIT_INSERT
|| type == EventType.POST_COMMIT_UPDATE ) {
listenerGroup = new PostCommitEventListenerGroupImpl<T>( type, this );
}
else {
listenerGroup = new EventListenerGroupImpl<T>( type, this );
}
if ( defaultListener != null ) {
listenerGroup.appendListener( defaultListener );
}
listenerArray[ type.ordinal() ] = listenerGroup;
}
private void addEventListeners(Map<EventType, Set<String>> eventListenerMap) {
if ( eventListenerMap == null ) {
return;
}
if ( this.eventListenerMap == null ) {
this.eventListenerMap = new HashMap<EventType, Set<String>>();
}
for ( Map.Entry<EventType, Set<String>> incomingEntry : eventListenerMap.entrySet() ) {
Set<String> listenerClasses = this.eventListenerMap.get( incomingEntry.getKey() );
if ( listenerClasses == null ) {
listenerClasses = new HashSet<String>();
this.eventListenerMap.put( incomingEntry.getKey(), listenerClasses );
}
listenerClasses.addAll( incomingEntry.getValue() );
}
}
protected <T> void appendListeners(EventListenerRegistry listenerRegistry,
EventType<T> eventType, Collection<T> listeners) {
EventListenerGroup<T> group = listenerRegistry.getEventListenerGroup(eventType);
for (T listener : listeners) {
if (listener != null) {
if(shouldOverrideListeners(eventType, listener)) {
// since ClosureEventTriggeringInterceptor extends DefaultSaveOrUpdateEventListener we want to override instead of append the listener here
// to avoid there being 2 implementations which would impact performance too
group.clear();
group.appendListener(listener);
}
else {
group.appendListener(listener);
}
}
}
}
private void postInsert() {
final EventListenerGroup<PostInsertEventListener> listenerGroup = listenerGroup( EventType.POST_INSERT );
if ( listenerGroup.isEmpty() ) {
return;
}
final PostInsertEvent event = new PostInsertEvent(
getInstance(),
getId(),
getState(),
getPersister(),
eventSource()
);
for ( PostInsertEventListener listener : listenerGroup.listeners() ) {
listener.onPostInsert( event );
}
}
protected CompletionStage<Void> reactiveAutoFlushIfRequired(Set<?> querySpaces) throws HibernateException {
checkOpen();
// if ( !isTransactionInProgress() ) {
// do not auto-flush while outside a transaction
// return CompletionStages.nullFuture();
// }
AutoFlushEvent event = new AutoFlushEvent( querySpaces, this );
return fire( event, EventType.AUTO_FLUSH, (DefaultReactiveAutoFlushEventListener l) -> l::reactiveOnAutoFlush );
}
private void preUpdate() {
final EventListenerGroup<PreCollectionUpdateEventListener> listenerGroup = listenerGroup( EventType.PRE_COLLECTION_UPDATE );
if ( listenerGroup.isEmpty() ) {
return;
}
final PreCollectionUpdateEvent event = new PreCollectionUpdateEvent(
getPersister(),
getCollection(),
eventSource()
);
for ( PreCollectionUpdateEventListener listener : listenerGroup.listeners() ) {
listener.onPreUpdateCollection( event );
}
}
private CompletionStage<Void> firePersistOnFlush(IdentitySet copiedAlready, PersistEvent event) {
pulseTransactionCoordinator();
return fire(event, copiedAlready, EventType.PERSIST_ONFLUSH,
(ReactivePersistEventListener l) -> l::reactiveOnPersist)
.whenComplete( (v, e) -> delayedAfterCompletion() );
}
private CompletionStage<Void> fireRefresh(IdentitySet refreshedAlready, RefreshEvent event) {
pulseTransactionCoordinator();
return fire(event, refreshedAlready, EventType.REFRESH,
(ReactiveRefreshEventListener l) -> l::reactiveOnRefresh)
.handle( (v, e) -> {
delayedAfterCompletion();
if (e instanceof RuntimeException) {
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
});
}
private CompletionStage<Void> fireLock(LockEvent event) {
pulseTransactionCoordinator();
return fire( event, EventType.LOCK, (ReactiveLockEventListener l) -> l::reactiveOnLock )
.handle( (v, e) -> {
delayedAfterCompletion();
if (e instanceof RuntimeException) {
throw getExceptionConverter().convert( (RuntimeException) e );
}
return CompletionStages.returnNullorRethrow( e );
});
}
@SuppressWarnings("unchecked")
private <E, L, RL, T> CompletionStage<T> fire(
E event,
EventType<L> eventType,
Function<RL, Function<E, CompletionStage<T>>> fun) {
CompletionStage<T> ret = CompletionStages.nullFuture();
for ( L listener : eventListeners( eventType ) ) {
//to preserve atomicity of the Session methods
//call apply() from within the arg of thenCompose()
ret = ret.thenCompose( v -> fun.apply((RL) listener).apply(event) );
}
return ret;
}
@SuppressWarnings("unchecked")
private <E,L,RL,P> CompletionStage<Void> fire(E event, P extra, EventType<L> eventType,
Function<RL, BiFunction<E, P, CompletionStage<Void>>> fun) {
CompletionStage<Void> ret = CompletionStages.nullFuture();
for ( L listener : eventListeners(eventType) ) {
//to preserve atomicity of the Session methods
//call apply() from within the arg of thenCompose()
ret = ret.thenCompose( v -> fun.apply((RL) listener).apply(event, extra) );
}
return ret;
}
@SuppressWarnings("deprecation")
private <T> Iterable<T> eventListeners(EventType<T> type) {
return getFactory().unwrap( SessionFactoryImplementor.class )
.getServiceRegistry().getService( EventListenerRegistry.class )
.getEventListenerGroup( type )
.listeners();
}
/**
* 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;
}
private void postRecreate() {
final EventListenerGroup<PostCollectionRecreateEventListener> listenerGroup = listenerGroup( EventType.POST_COLLECTION_RECREATE );
if ( listenerGroup.isEmpty() ) {
return;
}
final PostCollectionRecreateEvent event = new PostCollectionRecreateEvent( getPersister(), getCollection(), eventSource() );
for ( PostCollectionRecreateEventListener listener : listenerGroup.listeners() ) {
listener.onPostRecreateCollection( event );
}
}
@SuppressWarnings( {"UnusedDeclaration"})
public static void applyCallbackListeners(ValidatorFactory validatorFactory, ActivationContext activationContext) {
final Set<ValidationMode> modes = activationContext.getValidationModes();
if ( ! ( modes.contains( ValidationMode.CALLBACK ) || modes.contains( ValidationMode.AUTO ) ) ) {
return;
}
final ConfigurationService cfgService = activationContext.getServiceRegistry().getService( ConfigurationService.class );
final ClassLoaderService classLoaderService = activationContext.getServiceRegistry().getService( ClassLoaderService.class );
// de-activate not-null tracking at the core level when Bean Validation is present unless the user explicitly
// asks for it
if ( cfgService.getSettings().get( Environment.CHECK_NULLABILITY ) == null ) {
activationContext.getSessionFactory().getSessionFactoryOptions().setCheckNullability( false );
}
final BeanValidationEventListener listener = new BeanValidationEventListener(
validatorFactory,
cfgService.getSettings(),
classLoaderService
);
final EventListenerRegistry listenerRegistry = activationContext.getServiceRegistry()
.getService( EventListenerRegistry.class );
listenerRegistry.addDuplicationStrategy( DuplicationStrategyImpl.INSTANCE );
listenerRegistry.appendListeners( EventType.PRE_INSERT, listener );
listenerRegistry.appendListeners( EventType.PRE_UPDATE, listener );
listenerRegistry.appendListeners( EventType.PRE_DELETE, listener );
listener.initialize( cfgService.getSettings(), classLoaderService );
}