Search in sources :

Example 1 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project dropwizard by dropwizard.

the class SessionFactoryFactory method buildSessionFactory.

private SessionFactory buildSessionFactory(HibernateBundle<?> bundle, PooledDataSourceFactory dbConfig, ConnectionProvider connectionProvider, Map<String, String> properties, List<Class<?>> entities) {
    final Configuration configuration = new Configuration();
    configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed");
    configuration.setProperty(AvailableSettings.USE_SQL_COMMENTS, Boolean.toString(dbConfig.isAutoCommentsEnabled()));
    configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true");
    configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
    configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true");
    configuration.setProperty(AvailableSettings.ORDER_UPDATES, "true");
    configuration.setProperty(AvailableSettings.ORDER_INSERTS, "true");
    configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
    configuration.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
    for (Map.Entry<String, String> property : properties.entrySet()) {
        configuration.setProperty(property.getKey(), property.getValue());
    }
    addAnnotatedClasses(configuration, entities);
    bundle.configure(configuration);
    final ServiceRegistry registry = new StandardServiceRegistryBuilder().addService(ConnectionProvider.class, connectionProvider).applySettings(configuration.getProperties()).build();
    configure(configuration, registry);
    return configuration.buildSessionFactory(registry);
}
Also used : Configuration(org.hibernate.cfg.Configuration) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) ServiceRegistry(org.hibernate.service.ServiceRegistry) Map(java.util.Map)

Example 2 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class AbstractRegionAccessStrategyTest method mockedSession.

protected SharedSessionContractImplementor mockedSession() {
    SessionMock session = mock(SessionMock.class);
    when(session.isClosed()).thenReturn(false);
    when(session.getTimestamp()).thenReturn(TIME_SERVICE.wallClockTime());
    if (jtaPlatform == BatchModeJtaPlatform.class) {
        BatchModeTransactionCoordinator txCoord = new BatchModeTransactionCoordinator();
        when(session.getTransactionCoordinator()).thenReturn(txCoord);
        when(session.beginTransaction()).then(invocation -> {
            Transaction tx = txCoord.newTransaction();
            tx.begin();
            return tx;
        });
    } else if (jtaPlatform == null) {
        Connection connection = mock(Connection.class);
        JdbcConnectionAccess jdbcConnectionAccess = mock(JdbcConnectionAccess.class);
        try {
            when(jdbcConnectionAccess.obtainConnection()).thenReturn(connection);
        } catch (SQLException e) {
        // never thrown from mock
        }
        JdbcSessionOwner jdbcSessionOwner = mock(JdbcSessionOwner.class);
        when(jdbcSessionOwner.getJdbcConnectionAccess()).thenReturn(jdbcConnectionAccess);
        SqlExceptionHelper sqlExceptionHelper = mock(SqlExceptionHelper.class);
        JdbcServices jdbcServices = mock(JdbcServices.class);
        when(jdbcServices.getSqlExceptionHelper()).thenReturn(sqlExceptionHelper);
        ServiceRegistry serviceRegistry = mock(ServiceRegistry.class);
        when(serviceRegistry.getService(JdbcServices.class)).thenReturn(jdbcServices);
        JdbcSessionContext jdbcSessionContext = mock(JdbcSessionContext.class);
        when(jdbcSessionContext.getServiceRegistry()).thenReturn(serviceRegistry);
        when(jdbcSessionOwner.getJdbcSessionContext()).thenReturn(jdbcSessionContext);
        NonJtaTransactionCoordinator txOwner = mock(NonJtaTransactionCoordinator.class);
        when(txOwner.getResourceLocalTransaction()).thenReturn(new JdbcResourceTransactionMock());
        when(txOwner.getJdbcSessionOwner()).thenReturn(jdbcSessionOwner);
        when(txOwner.isActive()).thenReturn(true);
        TransactionCoordinator txCoord = JdbcResourceLocalTransactionCoordinatorBuilderImpl.INSTANCE.buildTransactionCoordinator(txOwner, null);
        when(session.getTransactionCoordinator()).thenReturn(txCoord);
        when(session.beginTransaction()).then(invocation -> {
            Transaction tx = new TransactionImpl(txCoord, session.getExceptionConverter());
            tx.begin();
            return tx;
        });
    } else {
        throw new IllegalStateException("Unknown JtaPlatform: " + jtaPlatform);
    }
    return session;
}
Also used : Arrays(java.util.Arrays) Connection(java.sql.Connection) BatchModeJtaPlatform(org.hibernate.test.cache.infinispan.util.BatchModeJtaPlatform) Cache(org.infinispan.Cache) Transaction(org.hibernate.Transaction) AdvancedCache(org.infinispan.AdvancedCache) After(org.junit.After) Mockito.doAnswer(org.mockito.Mockito.doAnswer) CacheDataDescriptionImpl(org.hibernate.cache.internal.CacheDataDescriptionImpl) TestingUtil(org.infinispan.test.TestingUtil) AccessType(org.hibernate.cache.spi.access.AccessType) Predicate(java.util.function.Predicate) TombstoneUpdate(org.hibernate.cache.infinispan.util.TombstoneUpdate) JdbcResourceTransactionAccess(org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransactionAccess) TestSynchronization(org.hibernate.test.cache.infinispan.util.TestSynchronization) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) SoftLock(org.hibernate.cache.spi.access.SoftLock) JdbcSessionOwner(org.hibernate.resource.jdbc.spi.JdbcSessionOwner) AfterClassOnce(org.hibernate.testing.AfterClassOnce) FutureUpdate(org.hibernate.cache.infinispan.util.FutureUpdate) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) TransactionImpl(org.hibernate.engine.transaction.internal.TransactionImpl) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) Mockito.mock(org.mockito.Mockito.mock) JdbcConnectionAccess(org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess) TestResourceTracker(org.infinispan.test.fwk.TestResourceTracker) Logger(org.jboss.logging.Logger) TransactionCoordinator(org.hibernate.resource.transaction.spi.TransactionCoordinator) Session(org.hibernate.Session) Caches(org.hibernate.cache.infinispan.util.Caches) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Mockito.spy(org.mockito.Mockito.spy) ArrayList(java.util.ArrayList) RegionAccessStrategy(org.hibernate.cache.spi.access.RegionAccessStrategy) SQLException(java.sql.SQLException) TestTimeService(org.hibernate.test.cache.infinispan.util.TestTimeService) RollbackException(javax.transaction.RollbackException) TransactionCoordinatorOwner(org.hibernate.resource.transaction.spi.TransactionCoordinatorOwner) ExpectingInterceptor(org.hibernate.test.cache.infinispan.util.ExpectingInterceptor) ComparableComparator(org.hibernate.internal.util.compare.ComparableComparator) BatchModeTransactionCoordinator(org.hibernate.test.cache.infinispan.util.BatchModeTransactionCoordinator) JdbcResourceTransactionMock(org.hibernate.test.cache.infinispan.util.JdbcResourceTransactionMock) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) AssertionFailedError(junit.framework.AssertionFailedError) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcSessionContext(org.hibernate.resource.jdbc.spi.JdbcSessionContext) TestInfinispanRegionFactory(org.hibernate.test.cache.infinispan.util.TestInfinispanRegionFactory) Mockito.when(org.mockito.Mockito.when) BaseRegion(org.hibernate.cache.infinispan.impl.BaseRegion) ServiceRegistry(org.hibernate.service.ServiceRegistry) TimeUnit(java.util.concurrent.TimeUnit) CacheDataDescription(org.hibernate.cache.spi.CacheDataDescription) InvalidateCommand(org.infinispan.commands.write.InvalidateCommand) Assert.assertNull(org.junit.Assert.assertNull) SystemException(javax.transaction.SystemException) JdbcResourceLocalTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl) SqlExceptionHelper(org.hibernate.engine.jdbc.spi.SqlExceptionHelper) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) Assert.assertEquals(org.junit.Assert.assertEquals) JdbcResourceTransactionMock(org.hibernate.test.cache.infinispan.util.JdbcResourceTransactionMock) JdbcSessionContext(org.hibernate.resource.jdbc.spi.JdbcSessionContext) SQLException(java.sql.SQLException) Connection(java.sql.Connection) TransactionCoordinator(org.hibernate.resource.transaction.spi.TransactionCoordinator) BatchModeTransactionCoordinator(org.hibernate.test.cache.infinispan.util.BatchModeTransactionCoordinator) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) TransactionImpl(org.hibernate.engine.transaction.internal.TransactionImpl) SqlExceptionHelper(org.hibernate.engine.jdbc.spi.SqlExceptionHelper) JdbcSessionOwner(org.hibernate.resource.jdbc.spi.JdbcSessionOwner) BatchModeTransactionCoordinator(org.hibernate.test.cache.infinispan.util.BatchModeTransactionCoordinator) Transaction(org.hibernate.Transaction) JdbcConnectionAccess(org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess) ServiceRegistry(org.hibernate.service.ServiceRegistry)

Example 3 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class ClassLoaderServiceImplTest method testStoppableClassLoaderService.

/**
     * HHH-8363 discovered multiple leaks within CLS.  Most notably, it wasn't getting GC'd due to holding
     * references to ServiceLoaders.  Ensure that the addition of Stoppable functionality cleans up properly.
     * 
     * TODO: Is there a way to test that the ServiceLoader was actually reset?
     */
@Test
@TestForIssue(jiraKey = "HHH-8363")
public void testStoppableClassLoaderService() {
    final BootstrapServiceRegistryBuilder bootstrapBuilder = new BootstrapServiceRegistryBuilder();
    bootstrapBuilder.applyClassLoader(new TestClassLoader());
    final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bootstrapBuilder.build()).build();
    final ClassLoaderService classLoaderService = serviceRegistry.getService(ClassLoaderService.class);
    TestIntegrator testIntegrator1 = findTestIntegrator(classLoaderService);
    assertNotNull(testIntegrator1);
    TestIntegrator testIntegrator2 = findTestIntegrator(classLoaderService);
    assertNotNull(testIntegrator2);
    assertSame(testIntegrator1, testIntegrator2);
    StandardServiceRegistryBuilder.destroy(serviceRegistry);
    try {
        findTestIntegrator(classLoaderService);
        Assert.fail("Should have thrown an HibernateException -- the ClassLoaderService instance was closed.");
    } catch (HibernateException e) {
        String message = e.getMessage();
        Assert.assertEquals("HHH000469: The ClassLoaderService can not be reused. This instance was stopped already.", message);
    }
}
Also used : BootstrapServiceRegistryBuilder(org.hibernate.boot.registry.BootstrapServiceRegistryBuilder) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) HibernateException(org.hibernate.HibernateException) ServiceRegistry(org.hibernate.service.ServiceRegistry) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 4 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class AuditedDynamicComponentTest method testAuditedDynamicComponentFailure.

//@Test
public void testAuditedDynamicComponentFailure() throws URISyntaxException {
    final Configuration config = new Configuration();
    final URL hbm = Thread.currentThread().getContextClassLoader().getResource("mappings/dynamicComponents/mapAudited.hbm.xml");
    config.addFile(new File(hbm.toURI()));
    final String auditStrategy = getAuditStrategy();
    if (!StringTools.isEmpty(auditStrategy)) {
        config.setProperty(EnversSettings.AUDIT_STRATEGY, auditStrategy);
    }
    final ServiceRegistry serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(config.getProperties());
    try {
        config.buildSessionFactory(serviceRegistry);
        Assert.fail("MappingException expected");
    } catch (MappingException e) {
        Assert.assertEquals("Audited dynamic-component properties are not supported. Consider applying @NotAudited annotation to " + AuditedDynamicComponentEntity.class.getName() + "#customFields.", e.getMessage());
    } finally {
        ServiceRegistryBuilder.destroy(serviceRegistry);
    }
}
Also used : Configuration(org.hibernate.cfg.Configuration) ServiceRegistry(org.hibernate.service.ServiceRegistry) File(java.io.File) URL(java.net.URL) MappingException(org.hibernate.MappingException)

Example 5 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class SchemaCreateHelper method toWriter.

public static void toWriter(Metadata metadata, Writer writer) {
    final ServiceRegistry serviceRegistry = ((MetadataImplementor) metadata).getMetadataBuildingOptions().getServiceRegistry();
    final Map settings = serviceRegistry.getService(ConfigurationService.class).getSettings();
    settings.put(AvailableSettings.HBM2DDL_SCRIPTS_ACTION, Action.CREATE);
    settings.put(AvailableSettings.HBM2DDL_SCRIPTS_CREATE_TARGET, writer);
    SchemaManagementToolCoordinator.process(metadata, serviceRegistry, settings, DelayedDropRegistryNotAvailableImpl.INSTANCE);
}
Also used : ServiceRegistry(org.hibernate.service.ServiceRegistry) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService) Map(java.util.Map)

Aggregations

ServiceRegistry (org.hibernate.service.ServiceRegistry)48 Test (org.junit.Test)27 MetadataSources (org.hibernate.boot.MetadataSources)18 BootstrapServiceRegistry (org.hibernate.boot.registry.BootstrapServiceRegistry)17 Configuration (org.hibernate.cfg.Configuration)14 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)11 AnnotationException (org.hibernate.AnnotationException)6 MappingException (org.hibernate.MappingException)6 SessionFactory (org.hibernate.SessionFactory)6 Metadata (org.hibernate.boot.Metadata)6 TestForIssue (org.hibernate.testing.TestForIssue)5 Map (java.util.Map)4 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)4 HibernateException (org.hibernate.HibernateException)3 ClassLoaderService (org.hibernate.boot.registry.classloading.spi.ClassLoaderService)3 ConfigurationService (org.hibernate.engine.config.spi.ConfigurationService)3 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2