Search in sources :

Example 6 with TestForIssue

use of org.hibernate.testing.TestForIssue in project hibernate-orm by hibernate.

the class InvalidationTest method testConcurrentRemoveAndPutFromLoad.

@Test
@TestForIssue(jiraKey = "HHH-9868")
public void testConcurrentRemoveAndPutFromLoad() throws Exception {
    final Item item = new Item("chris", "Chris's Item");
    withTxSession(s -> {
        s.persist(item);
    });
    Phaser deletePhaser = new Phaser(2);
    Phaser getPhaser = new Phaser(2);
    HookInterceptor hook = new HookInterceptor();
    AdvancedCache pendingPutsCache = getPendingPutsCache(Item.class);
    pendingPutsCache.addInterceptor(hook, 0);
    AtomicBoolean getThreadBlockedInDB = new AtomicBoolean(false);
    Thread deleteThread = new Thread(() -> {
        try {
            withTxSession(s -> {
                Item loadedItem = s.get(Item.class, item.getId());
                assertNotNull(loadedItem);
                arriveAndAwait(deletePhaser, 2000);
                arriveAndAwait(deletePhaser, 2000);
                log.trace("Item loaded");
                s.delete(loadedItem);
                s.flush();
                log.trace("Item deleted");
                arriveAndAwait(deletePhaser, 2000);
                arriveAndAwait(deletePhaser, 4000);
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }, "delete-thread");
    Thread getThread = new Thread(() -> {
        try {
            withTxSession(s -> {
                Item loadedItem = s.get(Item.class, item.getId());
                if (getThreadBlockedInDB.get()) {
                    assertNull(loadedItem);
                } else {
                    assertNotNull(loadedItem);
                }
            });
        } catch (PessimisticLockException e) {
            // (delete-thread has ITEMS table write-locked and we try to acquire read-lock)
            try {
                arriveAndAwait(getPhaser, 2000);
                arriveAndAwait(getPhaser, 2000);
            } catch (Exception e1) {
                throw new RuntimeException(e1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }, "get-thread");
    deleteThread.start();
    // deleteThread loads the entity
    arriveAndAwait(deletePhaser, 2000);
    withTx(() -> {
        sessionFactory().getCache().evictEntity(Item.class, item.getId());
        assertFalse(sessionFactory().getCache().containsEntity(Item.class, item.getId()));
        return null;
    });
    arriveAndAwait(deletePhaser, 2000);
    // delete thread invalidates PFER
    arriveAndAwait(deletePhaser, 2000);
    // get thread gets the entity from DB
    hook.block(getPhaser, getThread);
    getThread.start();
    try {
        arriveAndAwait(getPhaser, 2000);
    } catch (TimeoutException e) {
        getThreadBlockedInDB.set(true);
    }
    arriveAndAwait(deletePhaser, 2000);
    // delete thread finishes the remove from DB and cache
    deleteThread.join();
    hook.unblock();
    arriveAndAwait(getPhaser, 2000);
    // get thread puts the entry into cache
    getThread.join();
    assertNoInvalidators(pendingPutsCache);
    withTxSession(s -> {
        Item loadedItem = s.get(Item.class, item.getId());
        assertNull(loadedItem);
    });
}
Also used : Item(org.hibernate.test.cache.infinispan.functional.entities.Item) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AdvancedCache(org.infinispan.AdvancedCache) Phaser(java.util.concurrent.Phaser) TimeoutException(java.util.concurrent.TimeoutException) PessimisticLockException(org.hibernate.PessimisticLockException) PessimisticLockException(org.hibernate.PessimisticLockException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 7 with TestForIssue

use of org.hibernate.testing.TestForIssue in project hibernate-orm by hibernate.

the class LocalDateCustomSessionLevelTimeZoneTest method testTimeZone.

@Test
@TestForIssue(jiraKey = "HHH-11396")
public void testTimeZone() {
    TimeZone old = TimeZone.getDefault();
    try {
        // The producer (MySQL) Berlin and returns 1980-01-01
        TimeZone jdbcTimeZone = TimeZone.getTimeZone("Europe/Berlin");
        TimeZone.setDefault(jdbcTimeZone);
        //hibernate.connection.url jdbc:mysql://localhost/hibernate_orm_test
        doInHibernateSessionBuilder(() -> sessionFactory().withOptions().jdbcTimeZone(TIME_ZONE), s -> {
            Person person = new Person();
            person.id = 1L;
            s.persist(person);
        });
        doInHibernateSessionBuilder(() -> sessionFactory().withOptions().jdbcTimeZone(TIME_ZONE), s -> {
            Person person = s.find(Person.class, 1L);
            assertEquals(LocalDate.of(2017, 3, 7), person.createdOn);
        });
    } finally {
        TimeZone.setDefault(old);
    }
}
Also used : TimeZone(java.util.TimeZone) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 8 with TestForIssue

use of org.hibernate.testing.TestForIssue in project hibernate-orm by hibernate.

the class BeforeCompletionFailureTest method testUniqueConstraintViolationDuringManagedFlush.

@Test
@TestForIssue(jiraKey = "HHH-9888")
public void testUniqueConstraintViolationDuringManagedFlush() throws Exception {
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // set up test data
    Session session = openSession();
    session.getTransaction().begin();
    session.save(newEntity(1));
    session.getTransaction().commit();
    session.close();
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // do the test
    final TransactionManager tm = JtaPlatformStandardTestingImpl.INSTANCE.transactionManager();
    assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
    // begin the transaction ("CMT" style)
    tm.begin();
    session = openSession();
    session.save(newEntity(2));
    // which should lead to the UK violation
    try {
        tm.commit();
        fail("Expecting a failure from JTA commit");
    } catch (RollbackException expected) {
        log.info("Test encountered expected JTA RollbackException; looking for nested JDBCException", expected);
        boolean violationExceptionFound = false;
        Throwable cause = expected;
        while (cause != null) {
            if (cause instanceof JDBCException) {
                log.info("Found JDBCException, assuming related to UK violation", cause);
                violationExceptionFound = true;
                break;
            }
            cause = cause.getCause();
        }
        if (!violationExceptionFound) {
            fail("Did not find JDBCException in JTA RollbackException chain");
        }
    } finally {
        if (!((SessionImplementor) session).isClosed()) {
            session.close();
        }
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // clean up test data
    session = openSession();
    session.getTransaction().begin();
    session.createQuery("delete SimpleEntity").executeUpdate();
    session.getTransaction().commit();
    session.close();
}
Also used : JDBCException(org.hibernate.JDBCException) TransactionManager(javax.transaction.TransactionManager) RollbackException(javax.transaction.RollbackException) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 9 with TestForIssue

use of org.hibernate.testing.TestForIssue in project hibernate-orm by hibernate.

the class ForeignKeyNameTest method testJoinedSubclassForeignKeyNameIsNotAutoGeneratedWhenProvided.

@Test
@TestForIssue(jiraKey = "HHH-10247")
public void testJoinedSubclassForeignKeyNameIsNotAutoGeneratedWhenProvided() throws Exception {
    StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().applySetting(Environment.HBM2DDL_AUTO, "none").build();
    try {
        File output = File.createTempFile("update_script", ".sql");
        output.deleteOnExit();
        final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(ssr).addResource("org/hibernate/test/schemaupdate/manytomany/UserGroup.hbm.xml").buildMetadata();
        metadata.validate();
        new SchemaExport().setOutputFile(output.getAbsolutePath()).setDelimiter(";").setFormat(true).create(EnumSet.of(TargetType.SCRIPT), metadata);
        String fileContent = new String(Files.readAllBytes(output.toPath()));
        assertThat(fileContent.toLowerCase().contains("fk_user_group"), is(true));
        assertThat(fileContent.toLowerCase().contains("fk_group_user"), is(true));
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) File(java.io.File) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 10 with TestForIssue

use of org.hibernate.testing.TestForIssue in project hibernate-orm by hibernate.

the class JoinTableWithDefaultSchemaTest method testGetTableDataForJoinTableWithDefaultSchema.

@Test
@TestForIssue(jiraKey = "HHH-10978")
@RequiresDialect(SQLServerDialect.class)
public void testGetTableDataForJoinTableWithDefaultSchema() {
    StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().applySetting(AvailableSettings.DEFAULT_CATALOG, "hibernate_orm_test").applySetting(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false").build();
    try {
        final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(ssr).addAnnotatedClass(Task.class).addAnnotatedClass(Project.class).buildMetadata();
        metadata.validate();
        // first create the schema...
        new SchemaExport().create(EnumSet.of(TargetType.DATABASE), metadata);
        try {
            // validate the schema
            new SchemaValidator().validate(metadata);
        } finally {
            // cleanup
            new SchemaExport().drop(EnumSet.of(TargetType.DATABASE), metadata);
        }
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) MetadataSources(org.hibernate.boot.MetadataSources) SchemaValidator(org.hibernate.tool.hbm2ddl.SchemaValidator) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue) RequiresDialect(org.hibernate.testing.RequiresDialect)

Aggregations

TestForIssue (org.hibernate.testing.TestForIssue)649 Test (org.junit.Test)647 Session (org.hibernate.Session)357 EntityManager (javax.persistence.EntityManager)97 List (java.util.List)91 Transaction (org.hibernate.Transaction)88 MetadataSources (org.hibernate.boot.MetadataSources)47 ArrayList (java.util.ArrayList)38 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)38 Query (org.hibernate.Query)28 MetadataImplementor (org.hibernate.boot.spi.MetadataImplementor)25 Metadata (org.hibernate.boot.Metadata)24 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)24 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)23 Map (java.util.Map)22 CollectionEntry (org.hibernate.engine.spi.CollectionEntry)19 HashMap (java.util.HashMap)18 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)18 PersistentClass (org.hibernate.mapping.PersistentClass)18 HibernateException (org.hibernate.HibernateException)16