Java Code Examples for org.hibernate.Interceptor

The following examples show how to use org.hibernate.Interceptor. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: HibernateTransactionManager.java    License: MIT License 6 votes vote down vote up
/**
 * Return the current Hibernate entity interceptor, or {@code null} if none.
 * Resolves an entity interceptor bean name via the bean factory,
 * if necessary.
 * @throws IllegalStateException if bean name specified but no bean factory set
 * @throws BeansException if bean name resolution via the bean factory failed
 * @see #setEntityInterceptor
 * @see #setEntityInterceptorBeanName
 * @see #setBeanFactory
 */
@Nullable
public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException {
	if (this.entityInterceptor instanceof Interceptor) {
		return (Interceptor) this.entityInterceptor;
	}
	else if (this.entityInterceptor instanceof String) {
		if (this.beanFactory == null) {
			throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set");
		}
		String beanName = (String) this.entityInterceptor;
		return this.beanFactory.getBean(beanName, Interceptor.class);
	}
	else {
		return null;
	}
}
 
Example 2
/**
 * Return the current Hibernate entity interceptor, or {@code null} if none.
 * Resolves an entity interceptor bean name via the bean factory,
 * if necessary.
 * @throws IllegalStateException if bean name specified but no bean factory set
 * @throws BeansException if bean name resolution via the bean factory failed
 * @see #setEntityInterceptor
 * @see #setEntityInterceptorBeanName
 * @see #setBeanFactory
 */
@Nullable
public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException {
	if (this.entityInterceptor instanceof Interceptor) {
		return (Interceptor) this.entityInterceptor;
	}
	else if (this.entityInterceptor instanceof String) {
		if (this.beanFactory == null) {
			throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set");
		}
		String beanName = (String) this.entityInterceptor;
		return this.beanFactory.getBean(beanName, Interceptor.class);
	}
	else {
		return null;
	}
}
 
Example 3
/**
 * Return the current Hibernate entity interceptor, or {@code null} if none.
 * Resolves an entity interceptor bean name via the bean factory,
 * if necessary.
 * @throws IllegalStateException if bean name specified but no bean factory set
 * @throws BeansException if bean name resolution via the bean factory failed
 * @see #setEntityInterceptor
 * @see #setEntityInterceptorBeanName
 * @see #setBeanFactory
 */
public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException {
	if (this.entityInterceptor instanceof Interceptor) {
		return (Interceptor) entityInterceptor;
	}
	else if (this.entityInterceptor instanceof String) {
		if (this.beanFactory == null) {
			throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set");
		}
		String beanName = (String) this.entityInterceptor;
		return this.beanFactory.getBean(beanName, Interceptor.class);
	}
	else {
		return null;
	}
}
 
Example 4
/**
 * Return the current Hibernate entity interceptor, or {@code null} if none.
 * Resolves an entity interceptor bean name via the bean factory,
 * if necessary.
 * @throws IllegalStateException if bean name specified but no bean factory set
 * @throws BeansException if bean name resolution via the bean factory failed
 * @see #setEntityInterceptor
 * @see #setEntityInterceptorBeanName
 * @see #setBeanFactory
 */
public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException {
	if (this.entityInterceptor instanceof Interceptor) {
		return (Interceptor) entityInterceptor;
	}
	else if (this.entityInterceptor instanceof String) {
		if (this.beanFactory == null) {
			throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set");
		}
		String beanName = (String) this.entityInterceptor;
		return this.beanFactory.getBean(beanName, Interceptor.class);
	}
	else {
		return null;
	}
}
 
Example 5
@SuppressWarnings("deprecation")
private static Interceptor determineInterceptor(Map configurationSettings, StrategySelector strategySelector) {
	Object setting = configurationSettings.get( INTERCEPTOR );
	if ( setting == null ) {
		// try the legacy (deprecated) JPA name
		setting = configurationSettings.get( org.hibernate.jpa.AvailableSettings.INTERCEPTOR );
		if ( setting != null ) {
			DeprecationLogger.DEPRECATION_LOGGER.deprecatedSetting(
					org.hibernate.jpa.AvailableSettings.INTERCEPTOR,
					INTERCEPTOR
			);
		}
	}

	return strategySelector.resolveStrategy(
			Interceptor.class,
			setting
	);
}
 
Example 6
Source Project: onedev   Source File: DefaultPersistManager.java    License: MIT License 5 votes vote down vote up
@Inject
public DefaultPersistManager(PhysicalNamingStrategy physicalNamingStrategy,
		HibernateProperties properties, Interceptor interceptor, 
		IdManager idManager, Dao dao, EntityValidator validator, 
		TransactionManager transactionManager) {
	this.physicalNamingStrategy = physicalNamingStrategy;
	this.properties = properties;
	this.interceptor = interceptor;
	this.idManager = idManager;
	this.dao = dao;
	this.validator = validator;
	this.transactionManager = transactionManager;
	serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();
}
 
Example 7
Source Project: onedev   Source File: CleanDatabase.java    License: MIT License 5 votes vote down vote up
@Inject
public CleanDatabase(PhysicalNamingStrategy physicalNamingStrategy,
		HibernateProperties properties, Interceptor interceptor, 
		IdManager idManager, Dao dao, EntityValidator validator, 
		TransactionManager transactionManager) {
	super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator, transactionManager);
}
 
Example 8
Source Project: onedev   Source File: ApplyDatabaseConstraints.java    License: MIT License 5 votes vote down vote up
@Inject
public ApplyDatabaseConstraints(PhysicalNamingStrategy physicalNamingStrategy,
		HibernateProperties properties, Interceptor interceptor, 
		IdManager idManager, Dao dao, EntityValidator validator,
		TransactionManager transactionManager) {
	super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator, transactionManager);
}
 
Example 9
Source Project: onedev   Source File: RestoreDatabase.java    License: MIT License 5 votes vote down vote up
@Inject
public RestoreDatabase(PhysicalNamingStrategy physicalNamingStrategy,
		HibernateProperties properties, Interceptor interceptor, 
		IdManager idManager, Dao dao, EntityValidator validator, 
		TransactionManager transactionManager) {
	super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator, transactionManager);
}
 
Example 10
Source Project: onedev   Source File: ResetAdminPassword.java    License: MIT License 5 votes vote down vote up
@Inject
public ResetAdminPassword(PhysicalNamingStrategy physicalNamingStrategy, HibernateProperties properties, 
		Interceptor interceptor, IdManager idManager, Dao dao, 
		EntityValidator validator, UserManager userManager, PasswordService passwordService, 
		TransactionManager transactionManager) {
	super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator, transactionManager);
	this.userManager = userManager;
	this.passwordService = passwordService;
}
 
Example 11
Source Project: onedev   Source File: Upgrade.java    License: MIT License 5 votes vote down vote up
@Inject
public Upgrade(PhysicalNamingStrategy physicalNamingStrategy,
		HibernateProperties properties, Interceptor interceptor, 
		IdManager idManager, Dao dao, EntityValidator validator, 
		TransactionManager transactionManager) {
	super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator, transactionManager);
}
 
Example 12
Source Project: onedev   Source File: CheckDataVersion.java    License: MIT License 5 votes vote down vote up
@Inject
public CheckDataVersion(PhysicalNamingStrategy physicalNamingStrategy,
		HibernateProperties properties, Interceptor interceptor, 
		IdManager idManager, Dao dao, EntityValidator validator, 
		TransactionManager transactionManager) {
	super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator, transactionManager);
}
 
Example 13
Source Project: onedev   Source File: BackupDatabase.java    License: MIT License 5 votes vote down vote up
@Inject
public BackupDatabase(PhysicalNamingStrategy physicalNamingStrategy,
		HibernateProperties properties, Interceptor interceptor, 
		IdManager idManager, Dao dao, EntityValidator validator, 
		TransactionManager transactionManager) {
	super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator, transactionManager);
}
 
Example 14
Source Project: lams   Source File: SessionFactoryUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a new Hibernate Session from the given SessionFactory.
 * Will return a new Session even if there already is a pre-bound
 * Session for the given SessionFactory.
 * <p>Within a transaction, this method will create a new Session
 * that shares the transaction's JDBC Connection. More specifically,
 * it will use the same JDBC Connection as the pre-bound Hibernate Session.
 * @param sessionFactory Hibernate SessionFactory to create the session with
 * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none
 * @return the new Session
 */
public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) {
	Assert.notNull(sessionFactory, "No SessionFactory specified");

	try {
		SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
		if (sessionHolder != null && !sessionHolder.isEmpty()) {
			if (entityInterceptor != null) {
				return sessionFactory.openSession(sessionHolder.getAnySession().connection(), entityInterceptor);
			}
			else {
				return sessionFactory.openSession(sessionHolder.getAnySession().connection());
			}
		}
		else {
			if (entityInterceptor != null) {
				return sessionFactory.openSession(entityInterceptor);
			}
			else {
				return sessionFactory.openSession();
			}
		}
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 15
Source Project: lams   Source File: SessionFactoryImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static Interceptor configuredInterceptor(Interceptor interceptor, SessionFactoryOptions options) {
	// NOTE : DO NOT return EmptyInterceptor.INSTANCE from here as a "default for the Session"
	// 		we "filter" that one out here.  The return from here should represent the
	//		explicitly configured Interceptor (if one).  Return null from here instead; Session
	//		will handle it

	if ( interceptor != null && interceptor != EmptyInterceptor.INSTANCE ) {
		return interceptor;
	}

	// prefer the SF-scoped interceptor, prefer that to any Session-scoped interceptor prototype
	if ( options.getInterceptor() != null && options.getInterceptor() != EmptyInterceptor.INSTANCE ) {
		return options.getInterceptor();
	}

	// then check the Session-scoped interceptor prototype
	if ( options.getStatelessInterceptorImplementor() != null && options.getStatelessInterceptorImplementorSupplier() != null ) {
		throw new HibernateException(
				"A session scoped interceptor class or supplier are allowed, but not both!" );
	}
	else if ( options.getStatelessInterceptorImplementor() != null ) {
		try {
			/**
			 * We could remove the getStatelessInterceptorImplementor method and use just the getStatelessInterceptorImplementorSupplier
			 * since it can cover both cases when the user has given a Supplier<? extends Interceptor> or just the
			 * Class<? extends Interceptor>, in which case, we simply instantiate the Interceptor when calling the Supplier.
			 */
			return options.getStatelessInterceptorImplementor().newInstance();
		}
		catch (InstantiationException | IllegalAccessException e) {
			throw new HibernateException( "Could not supply session-scoped SessionFactory Interceptor", e );
		}
	}
	else if ( options.getStatelessInterceptorImplementorSupplier() != null ) {
		return options.getStatelessInterceptorImplementorSupplier().get();
	}

	return null;
}
 
Example 16
Source Project: lams   Source File: StandardCacheEntryImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Assemble the previously disassembled state represented by this entry into the given entity instance.
 *
 * Additionally manages the PreLoadEvent callbacks.
 *
 * @param instance The entity instance
 * @param id The entity identifier
 * @param persister The entity persister
 * @param interceptor (currently unused)
 * @param session The session
 *
 * @return The assembled state
 *
 * @throws HibernateException Indicates a problem performing assembly or calling the PreLoadEventListeners.
 *
 * @see org.hibernate.type.Type#assemble
 * @see org.hibernate.type.Type#disassemble
 */
public Object[] assemble(
		final Object instance,
		final Serializable id,
		final EntityPersister persister,
		final Interceptor interceptor,
		final EventSource session) throws HibernateException {
	if ( !persister.getEntityName().equals( subclass ) ) {
		throw new AssertionFailure( "Tried to assemble a different subclass instance" );
	}

	//assembled state gets put in a new array (we read from cache by value!)
	final Object[] state = TypeHelper.assemble(
			disassembledState,
			persister.getPropertyTypes(),
			session, instance
	);

	//persister.setIdentifier(instance, id); //before calling interceptor, for consistency with normal load

	//TODO: reuse the PreLoadEvent
	final PreLoadEvent preLoadEvent = new PreLoadEvent( session )
			.setEntity( instance )
			.setState( state )
			.setId( id )
			.setPersister( persister );

	final EventListenerGroup<PreLoadEventListener> listenerGroup = session
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( EventType.PRE_LOAD );
	for ( PreLoadEventListener listener : listenerGroup.listeners() ) {
		listener.onPreLoad( preLoadEvent );
	}

	persister.setPropertyValues( instance, state );

	return state;
}
 
Example 17
Source Project: lams   Source File: SessionFactoryOptions.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the interceptor to use by default for all sessions opened from this factory.
 *
 * @return The interceptor to use factory wide.  May be {@code null}
 */
default Supplier<? extends Interceptor> getStatelessInterceptorImplementorSupplier() {
	return () -> {
		try {
			return getStatelessInterceptorImplementor().newInstance();
		}
		catch (InstantiationException | IllegalAccessException e) {
			throw new HibernateException( "Could not supply session-scoped SessionFactory Interceptor", e );
		}
	};
}
 
Example 18
@SuppressWarnings({"unchecked", "deprecation"})
private static Supplier<? extends Interceptor> determineStatelessInterceptor(
		Map configurationSettings,
		StrategySelector strategySelector) {
	Object setting = configurationSettings.get( SESSION_SCOPED_INTERCEPTOR );
	if ( setting == null ) {
		// try the legacy (deprecated) JPA name
		setting = configurationSettings.get( org.hibernate.jpa.AvailableSettings.SESSION_INTERCEPTOR );
		if ( setting != null ) {
			DeprecationLogger.DEPRECATION_LOGGER.deprecatedSetting(
					org.hibernate.jpa.AvailableSettings.SESSION_INTERCEPTOR,
					SESSION_SCOPED_INTERCEPTOR
			);
		}
	}

	if ( setting == null ) {
		return null;
	}
	else if ( setting instanceof Supplier ) {
		return (Supplier<? extends Interceptor>) setting;
	}
	else if ( setting instanceof Class ) {
		Class<? extends Interceptor> clazz = (Class<? extends Interceptor>) setting;
		return interceptorSupplier( clazz );
	}
	else {
		return interceptorSupplier(
				strategySelector.selectStrategyImplementor(
						Interceptor.class,
						setting.toString()
				)
		);
	}
}
 
Example 19
private static Supplier<? extends Interceptor> interceptorSupplier(Class<? extends Interceptor> clazz) {
	return () -> {
		try {
			return clazz.newInstance();
		}
		catch (InstantiationException | IllegalAccessException e) {
			throw new HibernateException( "Could not supply session-scoped SessionFactory Interceptor", e );
		}
	};
}
 
Example 20
Source Project: hibernate-types   Source File: AbstractTest.java    License: Apache License 2.0 5 votes vote down vote up
private SessionFactory newSessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }
    configuration.setProperties(properties);
    return configuration.buildSessionFactory(
            new BootstrapServiceRegistryBuilder()
                    .build()
    );
}
 
Example 21
Source Project: hypersistence-optimizer   Source File: AbstractTest.java    License: Apache License 2.0 4 votes vote down vote up
protected Interceptor interceptor() {
    return null;
}
 
Example 22
Source Project: hypersistence-optimizer   Source File: AbstractTest.java    License: Apache License 2.0 4 votes vote down vote up
private SessionFactory newSessionFactory() {
    final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
        .enableAutoClose();

    final BootstrapServiceRegistry bsr = bsrb.build();

    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bsr)
        .applySettings(properties())
        .build();

    final MetadataSources metadataSources = new MetadataSources(serviceRegistry);

    for (Class annotatedClass : entities()) {
        metadataSources.addAnnotatedClass(annotatedClass);
    }

    String[] packages = packages();
    if (packages != null) {
        for (String annotatedPackage : packages) {
            metadataSources.addPackage(annotatedPackage);
        }
    }

    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            metadataSources.addResource(resource);
        }
    }

    final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
    metadataBuilder.enableNewIdentifierGeneratorSupport(true);

    MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();

    final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        sfb.applyInterceptor(interceptor);
    }

    return sfb.build();
}
 
Example 23
/**
 * process any unreferenced collections and then inspect all known collections,
 * scheduling creates/removes/updates
 */
private int flushCollections(final EventSource session, final PersistenceContext persistenceContext) throws HibernateException {
	LOG.trace( "Processing unreferenced collections" );

	final int count = persistenceContext.getCollectionEntriesSize();

	persistenceContext.forEachCollectionEntry(
			(persistentCollection, collectionEntry) -> {
				if ( !collectionEntry.isReached() && !collectionEntry.isIgnore() ) {
					Collections.processUnreachableCollection( persistentCollection, session );
				}
			}, true );

	// Schedule updates to collections:

	LOG.trace( "Scheduling collection removes/(re)creates/updates" );

	final ActionQueue actionQueue = session.getActionQueue();
	final Interceptor interceptor = session.getInterceptor();
	persistenceContext.forEachCollectionEntry(
			(coll, ce) -> {
				if ( ce.isDorecreate() ) {
					interceptor.onCollectionRecreate( coll, ce.getCurrentKey() );
					actionQueue.addAction(
							new CollectionRecreateAction(
									coll,
									ce.getCurrentPersister(),
									ce.getCurrentKey(),
									session
							)
					);
				}
				if ( ce.isDoremove() ) {
					interceptor.onCollectionRemove( coll, ce.getLoadedKey() );
					actionQueue.addAction(
							new CollectionRemoveAction(
									coll,
									ce.getLoadedPersister(),
									ce.getLoadedKey(),
									ce.isSnapshotEmpty( coll ),
									session
							)
					);
				}
				if ( ce.isDoupdate() ) {
					interceptor.onCollectionUpdate( coll, ce.getLoadedKey() );
					actionQueue.addAction(
							new CollectionUpdateAction(
									coll,
									ce.getLoadedPersister(),
									ce.getLoadedKey(),
									ce.isSnapshotEmpty( coll ),
									session
							)
					);
				}
				// todo : I'm not sure the !wasInitialized part should really be part of this check
				if ( !coll.wasInitialized() && coll.hasQueuedOperations() ) {
					actionQueue.addAction(
							new QueuedOperationCollectionAction(
									coll,
									ce.getLoadedPersister(),
									ce.getLoadedKey(),
									session
							)
					);
				}
			}, true );

	actionQueue.sortCollectionActions();

	return count;
}
 
Example 24
protected Session openSession(Interceptor interceptor) throws HibernateException {
  session = sessionFactory().withOptions().interceptor( interceptor ).openSession();
  return session;
}
 
Example 25
Source Project: hibernate-types   Source File: AbstractTest.java    License: Apache License 2.0 4 votes vote down vote up
private SessionFactory newLegacySessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        configuration.registerTypeContributor(new TypeContributor() {
            @Override
            public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
                for (Type type : additionalTypes) {
                    if (type instanceof BasicType) {
                        typeContributions.contributeType((BasicType) type);
                    } else if (type instanceof UserType) {
                        typeContributions.contributeType((UserType) type);
                    } else if (type instanceof CompositeUserType) {
                        typeContributions.contributeType((CompositeUserType) type);
                    }
                }
            }
        });
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 26
@Override
public Interceptor getInterceptor() {
	return delegate.getInterceptor();
}
 
Example 27
@Override
public Interceptor getInterceptor() {
	return delegate.getInterceptor();
}
 
Example 28
public CoordinatingEntityNameResolver(SessionFactoryImplementor sessionFactory, Interceptor interceptor) {
	this.sessionFactory = sessionFactory;
	this.interceptor = interceptor;
}
 
Example 29
Source Project: lams   Source File: SessionFactoryImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
public Interceptor getInterceptor() {
	return sessionFactoryOptions.getInterceptor();
}
 
Example 30
Source Project: lams   Source File: SessionFactoryImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public Interceptor getInterceptor() {
	return configuredInterceptor( interceptor, sessionFactory.getSessionFactoryOptions() );
}