use of org.hibernate.event.service.spi.EventListenerRegistry in project OpenOLAT by OpenOLAT.
the class DBImpl method appendPostUpdateEventListener.
public void appendPostUpdateEventListener(PostUpdateEventListener listener) {
SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(listener);
}
use of org.hibernate.event.service.spi.EventListenerRegistry in project hibernate-orm by hibernate.
the class EnversIntegrator method integrate.
public void integrate(Metadata metadata, BootstrapContext bootstrapContext, SessionFactoryImplementor sessionFactory) {
final ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
final EnversService enversService = serviceRegistry.getService(EnversService.class);
// Opt-out of registration if EnversService is disabled
if (!enversService.isEnabled()) {
log.debug("Skipping Envers listener registrations : EnversService disabled");
return;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Opt-out of registration if asked to not register
final boolean autoRegister = serviceRegistry.getService(ConfigurationService.class).getSetting(AUTO_REGISTER, StandardConverters.BOOLEAN, true);
if (!autoRegister) {
log.debug("Skipping Envers listener registrations : Listener auto-registration disabled");
return;
}
// Verify that the EnversService is fully initialized and ready to go.
if (!enversService.isInitialized()) {
throw new HibernateException("Expecting EnversService to have been initialized prior to call to EnversIntegrator#integrate");
}
// Opt-out of registration if no audited entities found
if (!enversService.getEntitiesConfigurations().hasAuditedEntities()) {
log.debug("Skipping Envers listener registrations : No audited entities found");
return;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Do the registrations
final EventListenerRegistry listenerRegistry = serviceRegistry.getService(EventListenerRegistry.class);
listenerRegistry.addDuplicationStrategy(EnversListenerDuplicationStrategy.INSTANCE);
if (enversService.getEntitiesConfigurations().hasAuditedEntities()) {
listenerRegistry.appendListeners(EventType.POST_DELETE, new EnversPostDeleteEventListenerImpl(enversService));
listenerRegistry.appendListeners(EventType.POST_INSERT, new EnversPostInsertEventListenerImpl(enversService));
listenerRegistry.appendListeners(EventType.PRE_UPDATE, new EnversPreUpdateEventListenerImpl(enversService));
listenerRegistry.appendListeners(EventType.POST_UPDATE, new EnversPostUpdateEventListenerImpl(enversService));
listenerRegistry.appendListeners(EventType.POST_COLLECTION_RECREATE, new EnversPostCollectionRecreateEventListenerImpl(enversService));
listenerRegistry.appendListeners(EventType.PRE_COLLECTION_REMOVE, new EnversPreCollectionRemoveEventListenerImpl(enversService));
listenerRegistry.appendListeners(EventType.PRE_COLLECTION_UPDATE, new EnversPreCollectionUpdateEventListenerImpl(enversService));
}
}
use of org.hibernate.event.service.spi.EventListenerRegistry in project hibernate-orm by hibernate.
the class HibernateQueryMetrics method bindTo.
@Override
public void bindTo(MeterRegistry meterRegistry) {
if (sessionFactory instanceof SessionFactoryImplementor) {
EventListenerRegistry eventListenerRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
MetricsEventHandler metricsEventHandler = new MetricsEventHandler(meterRegistry);
eventListenerRegistry.appendListeners(EventType.POST_LOAD, metricsEventHandler);
}
}
use of org.hibernate.event.service.spi.EventListenerRegistry in project candlepin by candlepin.
the class DatabaseTestFixture method insertValidationEventListeners.
/**
* There's no way to really get Guice to perform injections on stuff that
* the JpaPersistModule is creating, so we resort to grabbing the EntityManagerFactory
* after the fact and adding the Validation EventListener ourselves.
* @param inj
*/
private static void insertValidationEventListeners(Injector inj) {
Provider<EntityManagerFactory> emfProvider = inj.getProvider(EntityManagerFactory.class);
SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) emfProvider.get();
EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
Provider<BeanValidationEventListener> listenerProvider = inj.getProvider(BeanValidationEventListener.class);
registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(listenerProvider.get());
registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(listenerProvider.get());
registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(listenerProvider.get());
}
use of org.hibernate.event.service.spi.EventListenerRegistry in project domui by fjalvingh.
the class HibernateConfigurator method initialize.
/*--------------------------------------------------------------*/
/* CODING: Main initialization entrypoints. */
/*--------------------------------------------------------------*/
/**
* Main worker to initialize the database layer, using Hibernate, with a user-specified core data source. This
* code also enables SQL logging when .developer.properties option hibernate.sql=true.
*/
public static synchronized void initialize(final DataSource ds) throws Exception {
// Thanks to https://stackoverflow.com/questions/11639997/how-do-you-configure-logging-in-hibernate-4-to-use-slf4j
System.setProperty("org.jboss.logging.provider", "slf4j");
if (m_sessionFactory != null)
throw new IllegalStateException("HibernateConfigurator has already been initialized!");
if (m_annotatedClassList.size() == 0)
throw new IllegalStateException("Please call addClasses(Class<?>...) and register your Hibernate data classes before calling me.");
long ts = System.nanoTime();
m_dataSource = ds;
// see https://www.boraji.com/hibernate-5-event-listener-example
// -- Create Hibernate's config. See https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/chapters/bootstrap/Bootstrap.html
/*
* Hibernate apparently cannot initialize without the useless hibernate.cfg.xml file. We cannot
* add that file at the root location because that would interfere with applications. To have a
* working model we add it as a resource in this class's package. And of course Hibernate makes
* it hard to reach- we need to calculate the proper name, sigh.
*/
BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder().build();
String resname = "/" + HibernateConfigurator.class.getPackage().getName().replace('.', '/') + "/hibernate.cfg.xml";
StandardServiceRegistryBuilder serviceBuilder = new StandardServiceRegistryBuilder(bootstrapRegistry).configure(resname);
/*
* Set other properties according to config settings made.
*/
serviceBuilder.applySetting("hibernate.connection.datasource", ds);
boolean logsql;
if (m_showSQL == null)
// Take default from .developer.properties
logsql = DeveloperOptions.getBool("hibernate.sql", false);
else
logsql = m_showSQL.booleanValue();
if (logsql) {
serviceBuilder.applySetting("show_sql", "true");
serviceBuilder.applySetting("hibernate.show_sql", "true");
}
/*
* Hibernate defaults to completely non-standard behavior for sequences, using the
* "hilo" sequence generator by default. This irresponsible behavior means that
* by default Hibernate code is incompatible with any code using sequences.
* Since that is irresponsible and downright DUMB this reverts the behavior to
* using sequences in their normal behavior.
* See https://stackoverflow.com/questions/12745751/hibernate-sequencegenerator-and-allocationsize
*/
// MUST BE BEFORE config.configure
serviceBuilder.applySetting("hibernate.id.new_generator_mappings", "true");
m_hibernateOptions.forEach((option, value) -> serviceBuilder.applySetting(option, value));
if (DeveloperOptions.getBool("hibernate.format_sql", true)) {
serviceBuilder.applySetting("hibernate.format_sql", "true");
}
switch(m_mode) {
default:
throw new IllegalStateException("Mode: " + m_mode);
case CREATE:
serviceBuilder.applySetting("hbm2ddl.auto", "create");
serviceBuilder.applySetting("hibernate.hbm2ddl.auto", "create");
break;
case NONE:
serviceBuilder.applySetting("hbm2ddl.auto", "none");
serviceBuilder.applySetting("hibernate.hbm2ddl.auto", "none");
break;
case UPDATE:
serviceBuilder.applySetting("hbm2ddl.auto", "update");
serviceBuilder.applySetting("hibernate.hbm2ddl.auto", "update");
break;
}
// change settings
for (IHibernateConfigListener listener : m_onConfigureList) {
listener.onSettings(serviceBuilder);
}
ServiceRegistry reg = serviceBuilder.build();
MetadataSources sources = new MetadataSources(reg);
for (Class<?> clz : m_annotatedClassList) sources.addAnnotatedClass(clz);
// add classes
for (IHibernateConfigListener listener : m_onConfigureList) {
listener.onAddSources(sources);
}
Metadata metaData = sources.getMetadataBuilder().applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build();
enhanceMappings(metaData);
// for(Consumer<Configuration> listener : m_onConfigureList) {
// listener.accept(config);
// }
// -- Create the session factory: this completes the Hibernate config part.
SessionFactoryBuilder sessionFactoryBuilder = metaData.getSessionFactoryBuilder();
// sessionFactoryBuilder.applyInterceptor( new CustomSessionFactoryInterceptor() );
// sessionFactoryBuilder.addSessionFactoryObservers( new CustomSessionFactoryObserver() );
// Apply a CDI BeanManager ( for JPA event listeners )
// sessionFactoryBuilder.applyBeanManager( getBeanManager() );
SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) sessionFactoryBuilder.build();
m_sessionFactory = sessionFactory;
EventListenerRegistry listenerRegistry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
if (m_beforeImagesEnabled) {
// https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/events/Events.html
listenerRegistry.prependListeners(EventType.POST_LOAD, new CreateBeforeImagePostLoadListener());
listenerRegistry.prependListeners(EventType.INIT_COLLECTION, new CopyCollectionEventListener());
}
for (IHibernateConfigListener listener : m_onConfigureList) {
listener.onAddListeners(listenerRegistry);
}
// -- Start DomUI/WebApp.core initialization: generalized database layer
HibernateSessionMaker hsm;
if (m_interceptorFactory != null) {
// -- We need the copy interceptor to handle these.
hsm = dc -> {
Interceptor interceptor = dc.getAttribute(Interceptor.class);
// dc.setAttribute(Interceptor.class, interceptor);
return m_sessionFactory.withOptions().interceptor(interceptor).openSession();
// return m_sessionFactory.openSession(new BeforeImageInterceptor(dc.getBeforeCache()));
};
} else {
hsm = dc -> m_sessionFactory.openSession();
}
// -- If no handlers are registered: register the default ones.
if (m_handlers.size() == 0) {
m_handlers.register(JdbcQueryExecutor.FACTORY);
m_handlers.register(HibernateQueryExecutor.FACTORY);
}
m_contextSource = new HibernateLongSessionContextFactory(m_listeners, hsm, m_handlers, HibernateConfigurator::onContextCreated);
System.out.println("domui: Hibernate initialization took a whopping " + StringTool.strNanoTime(System.nanoTime() - ts));
}
Aggregations