下面列出了org.hibernate.usertype.UserType#org.hibernate.Interceptor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
}
/**
* 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;
}
}
/**
* 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;
}
}
/**
* 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;
}
}
@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
);
}
@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();
}
@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);
}
@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);
}
@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);
}
@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;
}
@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);
}
@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);
}
@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);
}
/**
* 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);
}
}
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;
}
/**
* 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;
}
/**
* 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 );
}
};
}
@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()
)
);
}
}
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 );
}
};
}
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()
);
}
protected Interceptor interceptor() {
return null;
}
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();
}
/**
* 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;
}
protected Session openSession(Interceptor interceptor) throws HibernateException {
session = sessionFactory().withOptions().interceptor( interceptor ).openSession();
return session;
}
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()
);
}
@Override
public Interceptor getInterceptor() {
return delegate.getInterceptor();
}
@Override
public Interceptor getInterceptor() {
return delegate.getInterceptor();
}
public CoordinatingEntityNameResolver(SessionFactoryImplementor sessionFactory, Interceptor interceptor) {
this.sessionFactory = sessionFactory;
this.interceptor = interceptor;
}
public Interceptor getInterceptor() {
return sessionFactoryOptions.getInterceptor();
}
@Override
public Interceptor getInterceptor() {
return configuredInterceptor( interceptor, sessionFactory.getSessionFactoryOptions() );
}