Search in sources :

Example 1 with SessionImpl

use of org.hibernate.internal.SessionImpl in project hibernate-orm by hibernate.

the class TestAutoFlushBeforeQueryExecution method testAutoflushIsNotRequiredWithUnrelatedCollectionChange.

@Test
public void testAutoflushIsNotRequiredWithUnrelatedCollectionChange() {
    Session s = openSession();
    Transaction txn = s.beginTransaction();
    Publisher publisher = new Publisher();
    publisher.setName("name");
    s.save(publisher);
    assertTrue("autoflush entity create", s.createQuery("from Publisher p").list().size() == 1);
    publisher.setName("name");
    assertTrue("autoflush entity update", s.createQuery("from Publisher p where p.name='name'").list().size() == 1);
    UnrelatedEntity unrelatedEntity = new UnrelatedEntity();
    s.save(unrelatedEntity);
    txn.commit();
    s.close();
    s = openSession();
    txn = s.beginTransaction();
    unrelatedEntity = (UnrelatedEntity) s.get(UnrelatedEntity.class, unrelatedEntity.getId());
    publisher = (Publisher) s.get(Publisher.class, publisher.getId());
    assertTrue(publisher.getAuthors().isEmpty());
    final PersistenceContext persistenceContext = ((SessionImplementor) s).getPersistenceContext();
    final ActionQueue actionQueue = ((SessionImpl) s).getActionQueue();
    assertEquals(1, persistenceContext.getCollectionEntries().size());
    assertEquals(1, persistenceContext.getCollectionsByKey().size());
    assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
    assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
    assertEquals(0, actionQueue.numberOfCollectionRemovals());
    Author author1 = new Author();
    author1.setPublisher(publisher);
    publisher.getAuthors().add(author1);
    assertTrue(s.createQuery("from UnrelatedEntity").list().size() == 1);
    assertEquals(2, persistenceContext.getCollectionEntries().size());
    assertEquals(1, persistenceContext.getCollectionsByKey().size());
    assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
    assertTrue(persistenceContext.getCollectionEntries().containsKey(author1.getBooks()));
    assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
    assertEquals(0, actionQueue.numberOfCollectionRemovals());
    author1.setPublisher(null);
    s.delete(author1);
    publisher.getAuthors().clear();
    assertEquals(0, actionQueue.numberOfCollectionRemovals());
    assertTrue(s.createQuery("from UnrelatedEntity").list().size() == 1);
    assertEquals(2, persistenceContext.getCollectionEntries().size());
    assertEquals(1, persistenceContext.getCollectionsByKey().size());
    assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
    assertTrue(persistenceContext.getCollectionEntries().containsKey(author1.getBooks()));
    assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
    assertEquals(0, actionQueue.numberOfCollectionRemovals());
    Set<Author> authorsOld = publisher.getAuthors();
    publisher.setAuthors(new HashSet<Author>());
    Author author2 = new Author();
    author2.setName("author2");
    author2.setPublisher(publisher);
    publisher.getAuthors().add(author2);
    List results = s.createQuery("from UnrelatedEntity").list();
    assertEquals(1, results.size());
    assertEquals(4, persistenceContext.getCollectionEntries().size());
    assertEquals(1, persistenceContext.getCollectionsByKey().size());
    assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
    assertTrue(persistenceContext.getCollectionEntries().containsKey(author2.getBooks()));
    assertTrue(persistenceContext.getCollectionEntries().containsKey(authorsOld));
    assertTrue(persistenceContext.getCollectionEntries().containsKey(author1.getBooks()));
    assertTrue(persistenceContext.getCollectionsByKey().values().contains(authorsOld));
    assertEquals(0, actionQueue.numberOfCollectionRemovals());
    s.flush();
    assertEquals(2, persistenceContext.getCollectionEntries().size());
    assertEquals(2, persistenceContext.getCollectionsByKey().size());
    assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
    assertTrue(persistenceContext.getCollectionEntries().containsKey(author2.getBooks()));
    assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
    assertTrue(persistenceContext.getCollectionsByKey().values().contains(author2.getBooks()));
    assertEquals(0, actionQueue.numberOfCollectionRemovals());
    s.delete(publisher);
    assertTrue("autoflush delete", s.createQuery("from UnrelatedEntity").list().size() == 1);
    s.delete(unrelatedEntity);
    txn.commit();
    s.close();
}
Also used : ActionQueue(org.hibernate.engine.spi.ActionQueue) Transaction(org.hibernate.Transaction) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) List(java.util.List) SessionImpl(org.hibernate.internal.SessionImpl) Session(org.hibernate.Session) Test(org.junit.Test)

Example 2 with SessionImpl

use of org.hibernate.internal.SessionImpl in project hibernate-orm by hibernate.

the class TransactionJoiningTest method testMultiThreadTransactionTimeout.

/**
 * In certain JTA environments (JBossTM, etc.), a background thread (reaper)
 * can rollback a transaction if it times out.  These timeouts are rare and
 * typically come from server failures.  However, we need to handle the
 * multi-threaded nature of the transaction afterCompletion action.
 * Emulate a timeout with a simple afterCompletion call in a thread.
 * See HHH-7910
 */
@Test
@TestForIssue(jiraKey = "HHH-7910")
public void testMultiThreadTransactionTimeout() throws Exception {
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    EntityManager em = entityManagerFactory().createEntityManager();
    final SessionImpl sImpl = em.unwrap(SessionImpl.class);
    final CountDownLatch latch = new CountDownLatch(1);
    Thread thread = new Thread() {

        public void run() {
            ((JtaTransactionCoordinatorImpl) sImpl.getTransactionCoordinator()).getSynchronizationCallbackCoordinator().afterCompletion(Status.STATUS_ROLLEDBACK);
            latch.countDown();
        }
    };
    thread.start();
    latch.await();
    boolean caught = false;
    try {
        em.persist(new Book("The Book of Foo", 1));
    } catch (PersistenceException e) {
        caught = e.getCause().getClass().equals(HibernateException.class);
    }
    assertTrue(caught);
    // Ensure that the connection was closed by the background thread.
    caught = false;
    try {
        em.createQuery("from Book").getResultList();
    } catch (PersistenceException e) {
        // HHH-9312
        caught = true;
    } catch (Exception e) {
        caught = true;
    }
    assertTrue(caught);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().rollback();
    em.close();
}
Also used : EntityManager(javax.persistence.EntityManager) PersistenceException(javax.persistence.PersistenceException) SessionImpl(org.hibernate.internal.SessionImpl) CountDownLatch(java.util.concurrent.CountDownLatch) TransactionRequiredException(javax.persistence.TransactionRequiredException) PersistenceException(javax.persistence.PersistenceException) HibernateException(org.hibernate.HibernateException) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 3 with SessionImpl

use of org.hibernate.internal.SessionImpl in project hibernate-orm by hibernate.

the class ParentChildTest method testReplicate.

@Test
@SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column")
public void testReplicate() throws Exception {
    Session s = openSession();
    s.beginTransaction();
    Container baz = new Container();
    Contained f = new Contained();
    List list = new ArrayList();
    list.add(baz);
    f.setBag(list);
    List list2 = new ArrayList();
    list2.add(f);
    baz.setBag(list2);
    s.save(f);
    s.save(baz);
    s.getTransaction().commit();
    s.close();
    s = openSession();
    s.beginTransaction();
    s.replicate(baz, ReplicationMode.OVERWRITE);
    // HHH-2378
    SessionImpl x = (SessionImpl) s;
    EntityEntry entry = x.getPersistenceContext().getEntry(baz);
    assertNull(entry.getVersion());
    // ~~~~~~~
    s.getTransaction().commit();
    s.close();
    s = openSession();
    s.beginTransaction();
    s.replicate(baz, ReplicationMode.IGNORE);
    s.getTransaction().commit();
    s.close();
    s = openSession();
    s.beginTransaction();
    s.delete(baz);
    s.delete(f);
    s.getTransaction().commit();
    s.close();
}
Also used : EntityEntry(org.hibernate.engine.spi.EntityEntry) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) SessionImpl(org.hibernate.internal.SessionImpl) Session(org.hibernate.Session) SkipForDialect(org.hibernate.testing.SkipForDialect) Test(org.junit.Test)

Example 4 with SessionImpl

use of org.hibernate.internal.SessionImpl in project evosuite by EvoSuite.

the class DBManagerIntTest method testDirectSQLModifications.

@Test
public void testDirectSQLModifications() throws SQLException {
    String tableName = "KVPair_table";
    Connection c = ((SessionImpl) DBManager.getInstance().getCurrentEntityManager().getDelegate()).connection();
    Statement s = c.createStatement();
    ResultSet rs = s.executeQuery("select * from " + tableName);
    // no data
    Assert.assertFalse(rs.next());
    rs.close();
    s.executeUpdate("INSERT INTO KVPair_table VALUES 'a', 'b'");
    rs = s.executeQuery("SELECT * from " + tableName);
    Assert.assertTrue(rs.next());
    String a = rs.getString(1);
    String b = rs.getString(2);
    rs.close();
    Assert.assertEquals("a", a);
    Assert.assertEquals("b", b);
    s.executeUpdate("DELETE from " + tableName);
    rs = s.executeQuery("select * from " + tableName);
    // no data
    Assert.assertFalse(rs.next());
    s.close();
}
Also used : Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SessionImpl(org.hibernate.internal.SessionImpl) Test(org.junit.Test)

Example 5 with SessionImpl

use of org.hibernate.internal.SessionImpl in project evosuite by EvoSuite.

the class DBManager method clearDatabase.

public boolean clearDatabase() {
    if (!wasAccessed) {
        return false;
    }
    try {
        // code adapted from https://objectpartners.com/2010/11/09/unit-testing-your-persistence-tier-code/
        Connection c = ((SessionImpl) em.getDelegate()).connection();
        Statement s = c.createStatement();
        s.execute("SET DATABASE REFERENTIAL INTEGRITY FALSE");
        Set<String> tables = new LinkedHashSet<>();
        ResultSet rs = s.executeQuery("select table_name " + "from INFORMATION_SCHEMA.system_tables " + "where table_type='TABLE' and table_schem='PUBLIC'");
        while (rs.next()) {
            if (!rs.getString(1).startsWith("DUAL_")) {
                tables.add(rs.getString(1));
            }
        }
        rs.close();
        for (String table : tables) {
            String delete = "DELETE FROM " + table;
            s.executeUpdate(delete);
            logger.debug("SQL executed: " + delete);
        }
        s.execute("SET DATABASE REFERENTIAL INTEGRITY TRUE");
        s.close();
        return true;
    } catch (Exception e) {
        AtMostOnceLogger.error(logger, "Failed to clear database: " + e);
        return false;
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SessionImpl(org.hibernate.internal.SessionImpl)

Aggregations

SessionImpl (org.hibernate.internal.SessionImpl)17 Test (org.junit.Test)9 List (java.util.List)5 Session (org.hibernate.Session)5 Connection (java.sql.Connection)4 ResultSet (java.sql.ResultSet)4 Statement (java.sql.Statement)4 EntityManager (javax.persistence.EntityManager)4 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)4 ClassMetadata (org.hibernate.metadata.ClassMetadata)4 Serializable (java.io.Serializable)3 Transaction (org.hibernate.Transaction)3 ArrayList (java.util.ArrayList)2 LinkedHashSet (java.util.LinkedHashSet)2 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)2 ActionQueue (org.hibernate.engine.spi.ActionQueue)2 EntityKey (org.hibernate.engine.spi.EntityKey)2 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)2 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)2 EntityPersister (org.hibernate.persister.entity.EntityPersister)2