Search in sources :

Example 26 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class SchemaUpdateSchemaNameTest method testSqlAlterWithTableSchemaName.

@Test
public void testSqlAlterWithTableSchemaName() throws Exception {
    StandardServiceRegistry ssr = null;
    try {
        final Configuration cfg = buildConfiguration(SimpleNext.class);
        ssr = new StandardServiceRegistryBuilder(new BootstrapServiceRegistryBuilder().build(), cfg.getStandardServiceRegistryBuilder().getAggregatedCfgXml()).applySettings(cfg.getProperties()).build();
        SessionFactory sf = cfg.buildSessionFactory(ssr);
        try {
            Session session = sf.openSession();
            try {
                session.getTransaction().begin();
                session.createQuery("FROM Simple", SimpleNext.class).getResultList();
                session.getTransaction().commit();
            } catch (Throwable t) {
                if (session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
                throw t;
            } finally {
                session.close();
            }
        } finally {
            sf.close();
        }
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) BootstrapServiceRegistryBuilder(org.hibernate.boot.registry.BootstrapServiceRegistryBuilder) Configuration(org.hibernate.cfg.Configuration) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) Session(org.hibernate.Session) Test(org.junit.Test)

Example 27 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class SessionFactoryRegistry method clearRegistrations.

public void clearRegistrations() {
    nameUuidXref.clear();
    for (SessionFactory factory : sessionFactoryMap.values()) {
        try {
            factory.close();
        } catch (Exception ignore) {
        }
    }
    sessionFactoryMap.clear();
}
Also used : SessionFactory(org.hibernate.SessionFactory) JndiException(org.hibernate.engine.jndi.JndiException) JndiNameException(org.hibernate.engine.jndi.JndiNameException)

Example 28 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class DropSchemaDuringJtaTxnTest method testDropDuringActiveJtaTransaction.

@Test
public void testDropDuringActiveJtaTransaction() throws Exception {
    final SessionFactory sessionFactory = buildSessionFactory();
    JtaPlatformStandardTestingImpl.INSTANCE.transactionManager().begin();
    try {
        sessionFactory.close();
    } finally {
        JtaPlatformStandardTestingImpl.INSTANCE.transactionManager().commit();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) Test(org.junit.Test)

Example 29 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class QueryRegionImplTest method testQueryUpdate.

@Test
public void testQueryUpdate() throws Exception {
    withQueryRegion((sessionFactory, region) -> {
        ExceptionHolder holder = new ExceptionHolder();
        CyclicBarrier barrier = new CyclicBarrier(2);
        withSession(sessionFactory, session -> region.put(session, KEY, VALUE1));
        Thread updater = new Thread() {

            @Override
            public void run() {
                try {
                    withSession(sessionFactory, (session) -> {
                        assertEquals(VALUE1, region.get(session, KEY));
                        region.put(session, KEY, VALUE2);
                        assertEquals(VALUE2, region.get(session, KEY));
                        barrier.await(5, TimeUnit.SECONDS);
                        barrier.await(5, TimeUnit.SECONDS);
                        region.put(session, KEY, VALUE3);
                        assertEquals(VALUE3, region.get(session, KEY));
                        barrier.await(5, TimeUnit.SECONDS);
                        barrier.await(5, TimeUnit.SECONDS);
                    });
                } catch (AssertionFailedError e) {
                    holder.addAssertionFailure(e);
                    barrier.reset();
                } catch (Exception e) {
                    holder.addException(e);
                    barrier.reset();
                }
            }
        };
        Thread reader = new Thread() {

            @Override
            public void run() {
                try {
                    withSession(sessionFactory, (session) -> {
                        assertEquals(VALUE1, region.get(session, KEY));
                        barrier.await(5, TimeUnit.SECONDS);
                        assertEquals(VALUE1, region.get(session, KEY));
                        barrier.await(5, TimeUnit.SECONDS);
                        barrier.await(5, TimeUnit.SECONDS);
                        assertEquals(VALUE1, region.get(session, KEY));
                        barrier.await(5, TimeUnit.SECONDS);
                    });
                } catch (AssertionFailedError e) {
                    holder.addAssertionFailure(e);
                    barrier.reset();
                } catch (Exception e) {
                    holder.addException(e);
                    barrier.reset();
                }
            }
        };
        updater.start();
        reader.start();
        updater.join();
        reader.join();
        holder.checkExceptions();
        assertEquals(VALUE3, callWithSession(sessionFactory, session -> region.get(session, KEY)));
    });
}
Also used : InfinispanRegionFactory(org.hibernate.cache.infinispan.InfinispanRegionFactory) QueryResultsRegionImpl(org.hibernate.cache.infinispan.query.QueryResultsRegionImpl) Logger(org.jboss.logging.Logger) CacheEntryModifiedEvent(org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent) CacheEntryVisitedEvent(org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent) Session(org.hibernate.Session) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) QueryResultsRegion(org.hibernate.cache.spi.QueryResultsRegion) ArrayList(java.util.ArrayList) Transaction(org.hibernate.Transaction) TestForIssue(org.hibernate.testing.TestForIssue) CacheEntryVisited(org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited) AdvancedCache(org.infinispan.AdvancedCache) CacheEntryModified(org.infinispan.notifications.cachelistener.annotation.CacheEntryModified) CyclicBarrier(java.util.concurrent.CyclicBarrier) Properties(java.util.Properties) Listener(org.infinispan.notifications.Listener) SessionFactory(org.hibernate.SessionFactory) CacheTestUtil(org.hibernate.test.cache.infinispan.util.CacheTestUtil) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) AssertionFailedError(junit.framework.AssertionFailedError) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) StandardQueryCache(org.hibernate.cache.internal.StandardQueryCache) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CacheDataDescription(org.hibernate.cache.spi.CacheDataDescription) IsolationLevel(org.infinispan.util.concurrent.IsolationLevel) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) Region(org.hibernate.cache.spi.Region) AbstractGeneralDataRegionTest(org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTest) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) AssertionFailedError(junit.framework.AssertionFailedError) CyclicBarrier(java.util.concurrent.CyclicBarrier) Test(org.junit.Test) AbstractGeneralDataRegionTest(org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTest)

Example 30 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class CorrectnessTestCase method beforeClass.

@BeforeClassOnce
public void beforeClass() {
    TestResourceTracker.testStarted(getClass().getSimpleName());
    Arrays.asList(new File(System.getProperty("java.io.tmpdir")).listFiles((dir, name) -> name.startsWith("family_") || name.startsWith("invalidations-"))).stream().forEach(f -> f.delete());
    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().enableAutoClose().applySetting(Environment.USE_SECOND_LEVEL_CACHE, "true").applySetting(Environment.USE_QUERY_CACHE, "true").applySetting(Environment.DRIVER, "org.h2.Driver").applySetting(Environment.URL, "jdbc:h2:mem:" + getDbName() + ";TRACE_LEVEL_FILE=4").applySetting(Environment.DIALECT, H2Dialect.class.getName()).applySetting(Environment.HBM2DDL_AUTO, "create-drop").applySetting(Environment.CACHE_REGION_FACTORY, FailingInfinispanRegionFactory.class.getName()).applySetting(TestInfinispanRegionFactory.CACHE_MODE, cacheMode).applySetting(Environment.USE_MINIMAL_PUTS, "false").applySetting(Environment.GENERATE_STATISTICS, "false");
    applySettings(ssrb);
    sessionFactories = new SessionFactory[NUM_NODES];
    for (int i = 0; i < NUM_NODES; ++i) {
        StandardServiceRegistry registry = ssrb.build();
        Metadata metadata = buildMetadata(registry);
        sessionFactories[i] = metadata.buildSessionFactory();
    }
}
Also used : Arrays(java.util.Arrays) ConfigurationBuilder(org.infinispan.configuration.cache.ConfigurationBuilder) Transaction(org.hibernate.Transaction) Future(java.util.concurrent.Future) PessimisticLockException(org.hibernate.PessimisticLockException) PersistentClass(org.hibernate.mapping.PersistentClass) Map(java.util.Map) StaleStateException(org.hibernate.StaleStateException) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) Category(org.junit.experimental.categories.Category) Executors(java.util.concurrent.Executors) InvocationTargetException(java.lang.reflect.InvocationTargetException) InterceptorConfiguration(org.infinispan.configuration.cache.InterceptorConfiguration) Stream(java.util.stream.Stream) AfterClassOnce(org.hibernate.testing.AfterClassOnce) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) TestingJtaPlatformImpl(org.hibernate.testing.jta.TestingJtaPlatformImpl) InfinispanRegionFactory(org.hibernate.cache.infinispan.InfinispanRegionFactory) H2Dialect(org.hibernate.dialect.H2Dialect) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) TestResourceTracker(org.infinispan.test.fwk.TestResourceTracker) RunWith(org.junit.runner.RunWith) SimpleDateFormat(java.text.SimpleDateFormat) Session(org.hibernate.Session) Metadata(org.hibernate.boot.Metadata) ArrayList(java.util.ArrayList) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BiConsumer(java.util.function.BiConsumer) JtaTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl) Environment(org.hibernate.cfg.Environment) Family(org.hibernate.test.cache.infinispan.stress.entities.Family) Properties(java.util.Properties) Files(java.nio.file.Files) BlockingDeque(java.util.concurrent.BlockingDeque) BufferedWriter(java.io.BufferedWriter) OptimisticLockException(javax.persistence.OptimisticLockException) RollbackCommand(org.infinispan.commands.tx.RollbackCommand) IOException(java.io.IOException) Test(org.junit.Test) TestInfinispanRegionFactory(org.hibernate.test.cache.infinispan.util.TestInfinispanRegionFactory) Field(java.lang.reflect.Field) File(java.io.File) TreeMap(java.util.TreeMap) JdbcResourceLocalTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl) ForkJoinPool(java.util.concurrent.ForkJoinPool) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) InfinispanMessageLogger(org.hibernate.cache.infinispan.util.InfinispanMessageLogger) Date(java.util.Date) TransactionStatus(org.hibernate.resource.transaction.spi.TransactionStatus) Person(org.hibernate.test.cache.infinispan.stress.entities.Person) JtaAwareConnectionProviderImpl(org.hibernate.testing.jta.JtaAwareConnectionProviderImpl) InvocationContext(org.infinispan.context.InvocationContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AccessType(org.hibernate.cache.spi.access.AccessType) Method(java.lang.reflect.Method) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Parameterized(org.junit.runners.Parameterized) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) StaleObjectStateException(org.hibernate.StaleObjectStateException) Collection(org.hibernate.mapping.Collection) NavigableMap(java.util.NavigableMap) Collectors(java.util.stream.Collectors) TransactionException(org.hibernate.TransactionException) MetadataSources(org.hibernate.boot.MetadataSources) List(java.util.List) PersistenceException(javax.persistence.PersistenceException) Address(org.hibernate.test.cache.infinispan.stress.entities.Address) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) TimeoutException(org.infinispan.util.concurrent.TimeoutException) Restrictions(org.hibernate.criterion.Restrictions) RootClass(org.hibernate.mapping.RootClass) HashMap(java.util.HashMap) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) ConcurrentMap(java.util.concurrent.ConcurrentMap) RegionAccessStrategy(org.hibernate.cache.spi.access.RegionAccessStrategy) HashSet(java.util.HashSet) RollbackException(javax.transaction.RollbackException) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) ForkJoinTask(java.util.concurrent.ForkJoinTask) LockMode(org.hibernate.LockMode) Iterator(java.util.Iterator) CustomParameterized(org.hibernate.testing.junit4.CustomParameterized) NoJtaPlatform(org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform) CommitCommand(org.infinispan.commands.tx.CommitCommand) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) CacheMode(org.infinispan.configuration.cache.CacheMode) BaseCustomInterceptor(org.infinispan.interceptors.base.BaseCustomInterceptor) Ignore(org.junit.Ignore) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) VisitableCommand(org.infinispan.commands.VisitableCommand) Comparator(java.util.Comparator) TransactionManager(javax.transaction.TransactionManager) InvalidationCacheAccessDelegate(org.hibernate.cache.infinispan.access.InvalidationCacheAccessDelegate) RemoteException(org.infinispan.remoting.RemoteException) Collections(java.util.Collections) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) File(java.io.File) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce)

Aggregations

SessionFactory (org.hibernate.SessionFactory)108 Test (org.junit.Test)62 Session (org.hibernate.Session)50 Configuration (org.hibernate.cfg.Configuration)35 Transaction (org.hibernate.Transaction)20 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)19 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)13 MetadataSources (org.hibernate.boot.MetadataSources)11 HibernateEntityManagerFactory (org.hibernate.jpa.HibernateEntityManagerFactory)9 TestForIssue (org.hibernate.testing.TestForIssue)9 Properties (java.util.Properties)8 Query (org.hibernate.Query)8 Metadata (org.hibernate.boot.Metadata)8 ArrayList (java.util.ArrayList)7 InfinispanRegionFactory (org.hibernate.cache.infinispan.InfinispanRegionFactory)7 List (java.util.List)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 TimeUnit (java.util.concurrent.TimeUnit)5 AnnotationException (org.hibernate.AnnotationException)5 Collections (java.util.Collections)4