Search in sources :

Example 76 with SessionImplementor

use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.

the class BasicConnectionTest method testExceptionHandling.

@Test
public void testExceptionHandling() {
    Session session = openSession();
    SessionImplementor sessionImpl = (SessionImplementor) session;
    boolean caught = false;
    try {
        PreparedStatement ps = sessionImpl.getJdbcCoordinator().getStatementPreparer().prepareStatement("select count(*) from NON_EXISTENT");
        sessionImpl.getJdbcCoordinator().getResultSetReturn().execute(ps);
    } catch (JDBCException ok) {
        caught = true;
    } finally {
        session.close();
    }
    assertTrue("The connection did not throw a JDBCException as expected", caught);
}
Also used : JDBCException(org.hibernate.JDBCException) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) PreparedStatement(java.sql.PreparedStatement) Session(org.hibernate.Session) Test(org.junit.Test)

Example 77 with SessionImplementor

use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.

the class BatchingTest method testBatchingUsage.

@Test
public void testBatchingUsage() throws Exception {
    Session session = openSession();
    SessionImplementor sessionImpl = (SessionImplementor) session;
    final JdbcCoordinator jdbcCoordinator = sessionImpl.getJdbcCoordinator();
    LogicalConnectionImplementor logicalConnection = jdbcCoordinator.getLogicalConnection();
    // set up some tables to use
    Statement statement = jdbcCoordinator.getStatementPreparer().createStatement();
    String dropSql = getDialect().getDropTableString("SANDBOX_JDBC_TST");
    try {
        jdbcCoordinator.getResultSetReturn().execute(statement, dropSql);
    } catch (Exception e) {
    // ignore if the DB doesn't support "if exists" and the table doesn't exist
    }
    jdbcCoordinator.getResultSetReturn().execute(statement, "create table SANDBOX_JDBC_TST ( ID integer, NAME varchar(100) )");
    assertTrue(jdbcCoordinator.getResourceRegistry().hasRegisteredResources());
    assertTrue(logicalConnection.isPhysicallyConnected());
    jdbcCoordinator.getResourceRegistry().release(statement);
    assertFalse(jdbcCoordinator.getResourceRegistry().hasRegisteredResources());
    // after_transaction specified
    assertTrue(logicalConnection.isPhysicallyConnected());
    // ok, now we can get down to it...
    // same as Session#getTransaction
    Transaction txn = session.getTransaction();
    txn.begin();
    final BatchBuilder batchBuilder = new BatchBuilderImpl(2);
    final BatchKey batchKey = new BasicBatchKey("this", Expectations.BASIC);
    final Batch insertBatch = batchBuilder.buildBatch(batchKey, jdbcCoordinator);
    assertTrue("unexpected Batch impl", BatchingBatch.class.isInstance(insertBatch));
    final JournalingBatchObserver batchObserver = new JournalingBatchObserver();
    insertBatch.addObserver(batchObserver);
    final String insertSql = "insert into SANDBOX_JDBC_TST( ID, NAME ) values ( ?, ? )";
    PreparedStatement insert = insertBatch.getBatchStatement(insertSql, false);
    insert.setLong(1, 1);
    insert.setString(2, "name");
    assertEquals(0, batchObserver.getExplicitExecutionCount());
    assertEquals(0, batchObserver.getImplicitExecutionCount());
    insertBatch.addToBatch();
    assertEquals(0, batchObserver.getExplicitExecutionCount());
    assertEquals(0, batchObserver.getImplicitExecutionCount());
    assertTrue(jdbcCoordinator.getResourceRegistry().hasRegisteredResources());
    PreparedStatement insert2 = insertBatch.getBatchStatement(insertSql, false);
    assertSame(insert, insert2);
    insert = insert2;
    insert.setLong(1, 2);
    insert.setString(2, "another name");
    assertEquals(0, batchObserver.getExplicitExecutionCount());
    assertEquals(0, batchObserver.getImplicitExecutionCount());
    insertBatch.addToBatch();
    assertEquals(0, batchObserver.getExplicitExecutionCount());
    assertEquals(1, batchObserver.getImplicitExecutionCount());
    assertTrue(jdbcCoordinator.getResourceRegistry().hasRegisteredResources());
    insertBatch.execute();
    assertEquals(1, batchObserver.getExplicitExecutionCount());
    assertEquals(1, batchObserver.getImplicitExecutionCount());
    assertFalse(jdbcCoordinator.getResourceRegistry().hasRegisteredResources());
    insertBatch.release();
    txn.commit();
    session.close();
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) LogicalConnectionImplementor(org.hibernate.resource.jdbc.spi.LogicalConnectionImplementor) BatchBuilder(org.hibernate.engine.jdbc.batch.spi.BatchBuilder) PreparedStatement(java.sql.PreparedStatement) JdbcCoordinator(org.hibernate.engine.jdbc.spi.JdbcCoordinator) JournalingBatchObserver(org.hibernate.test.common.JournalingBatchObserver) Transaction(org.hibernate.Transaction) NonBatchingBatch(org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch) Batch(org.hibernate.engine.jdbc.batch.spi.Batch) BatchingBatch(org.hibernate.engine.jdbc.batch.internal.BatchingBatch) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) BasicBatchKey(org.hibernate.engine.jdbc.batch.internal.BasicBatchKey) BatchKey(org.hibernate.engine.jdbc.batch.spi.BatchKey) BasicBatchKey(org.hibernate.engine.jdbc.batch.internal.BasicBatchKey) NonBatchingBatch(org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch) BatchingBatch(org.hibernate.engine.jdbc.batch.internal.BatchingBatch) BatchBuilderImpl(org.hibernate.engine.jdbc.batch.internal.BatchBuilderImpl) Session(org.hibernate.Session) Test(org.junit.Test)

Example 78 with SessionImplementor

use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.

the class ReadOnlySessionLazyNonLazyTest method checkObject.

private void checkObject(Object entityOrProxy, Set expectedInitializedObjects, Set expectedReadOnlyObjects, Session s) {
    boolean isExpectedToBeInitialized = expectedInitializedObjects.contains(entityOrProxy);
    boolean isExpectedToBeReadOnly = expectedReadOnlyObjects.contains(entityOrProxy);
    SessionImplementor si = (SessionImplementor) s;
    assertEquals(isExpectedToBeInitialized, Hibernate.isInitialized(entityOrProxy));
    assertEquals(isExpectedToBeReadOnly, s.isReadOnly(entityOrProxy));
    if (Hibernate.isInitialized(entityOrProxy)) {
        Object entity = (entityOrProxy instanceof HibernateProxy ? ((HibernateProxy) entityOrProxy).getHibernateLazyInitializer().getImplementation(si) : entityOrProxy);
        assertNotNull(entity);
        assertEquals(isExpectedToBeReadOnly, s.isReadOnly(entity));
    }
}
Also used : SessionImplementor(org.hibernate.engine.spi.SessionImplementor) HibernateProxy(org.hibernate.proxy.HibernateProxy)

Example 79 with SessionImplementor

use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.

the class BasicStreamTest method basicStreamTest.

@Test
public void basicStreamTest() {
    Session session = openSession();
    session.getTransaction().begin();
    // mainly we want to make sure that closing the Stream releases the ScrollableResults too
    assertThat(((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry().hasRegisteredResources(), is(false));
    final Stream<MyEntity> stream = session.createQuery("from MyEntity", MyEntity.class).stream();
    assertThat(((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry().hasRegisteredResources(), is(true));
    stream.forEach(System.out::println);
    assertThat(((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry().hasRegisteredResources(), is(true));
    stream.close();
    assertThat(((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry().hasRegisteredResources(), is(false));
    session.getTransaction().commit();
    session.close();
}
Also used : SessionImplementor(org.hibernate.engine.spi.SessionImplementor) Session(org.hibernate.Session) Test(org.junit.Test)

Example 80 with SessionImplementor

use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.

the class ValidityAuditStrategy method perform.

@Override
public void perform(final Session session, final String entityName, final AuditEntitiesConfiguration audEntitiesCfg, final Serializable id, final Object data, final Object revision) {
    final String auditedEntityName = audEntitiesCfg.getAuditEntityName(entityName);
    final String revisionInfoEntityName = audEntitiesCfg.getRevisionInfoEntityName();
    // Save the audit data
    session.save(auditedEntityName, data);
    // Update the end date of the previous row.
    //
    // When application reuses identifiers of previously removed entities:
    // The UPDATE statement will no-op if an entity with a given identifier has been
    // inserted for the first time. But in case a deleted primary key value was
    // reused, this guarantees correct strategy behavior: exactly one row with
    // null end date exists for each identifier.
    final boolean reuseEntityIdentifier = audEntitiesCfg.getEnversService().getGlobalConfiguration().isAllowIdentifierReuse();
    if (reuseEntityIdentifier || getRevisionType(audEntitiesCfg, data) != RevisionType.ADD) {
        // Register transaction completion process to guarantee execution of UPDATE statement afterQuery INSERT.
        ((EventSource) session).getActionQueue().registerProcess(new BeforeTransactionCompletionProcess() {

            @Override
            public void doBeforeTransactionCompletion(final SessionImplementor sessionImplementor) {
                final Queryable productionEntityQueryable = getQueryable(entityName, sessionImplementor);
                final Queryable rootProductionEntityQueryable = getQueryable(productionEntityQueryable.getRootEntityName(), sessionImplementor);
                final Queryable auditedEntityQueryable = getQueryable(auditedEntityName, sessionImplementor);
                final Queryable rootAuditedEntityQueryable = getQueryable(auditedEntityQueryable.getRootEntityName(), sessionImplementor);
                final String updateTableName;
                if (UnionSubclassEntityPersister.class.isInstance(rootProductionEntityQueryable)) {
                    // this is the condition causing all the problems in terms of the generated SQL UPDATE
                    // the problem being that we currently try to update the in-line view made up of the union query
                    //
                    // this is extremely hacky means to get the root table name for the union subclass style entities.
                    // hacky because it relies on internal behavior of UnionSubclassEntityPersister
                    // !!!!!! NOTICE - using subclass persister, not root !!!!!!
                    updateTableName = auditedEntityQueryable.getSubclassTableName(0);
                } else {
                    updateTableName = rootAuditedEntityQueryable.getTableName();
                }
                final Type revisionInfoIdType = sessionImplementor.getFactory().getMetamodel().entityPersister(revisionInfoEntityName).getIdentifierType();
                final String revEndColumnName = rootAuditedEntityQueryable.toColumns(audEntitiesCfg.getRevisionEndFieldName())[0];
                final boolean isRevisionEndTimestampEnabled = audEntitiesCfg.isRevisionEndTimestampEnabled();
                // update audit_ent set REVEND = ? [, REVEND_TSTMP = ?] where (prod_ent_id) = ? and REV <> ? and REVEND is null
                final Update update = new Update(sessionImplementor.getFactory().getJdbcServices().getDialect()).setTableName(updateTableName);
                // set REVEND = ?
                update.addColumn(revEndColumnName);
                // set [, REVEND_TSTMP = ?]
                if (isRevisionEndTimestampEnabled) {
                    update.addColumn(rootAuditedEntityQueryable.toColumns(audEntitiesCfg.getRevisionEndTimestampFieldName())[0]);
                }
                // where (prod_ent_id) = ?
                update.addPrimaryKeyColumns(rootProductionEntityQueryable.getIdentifierColumnNames());
                // where REV <> ?
                update.addWhereColumn(rootAuditedEntityQueryable.toColumns(audEntitiesCfg.getRevisionNumberPath())[0], "<> ?");
                // where REVEND is null
                update.addWhereColumn(revEndColumnName, " is null");
                // Now lets execute the sql...
                final String updateSql = update.toStatementString();
                int rowCount = sessionImplementor.doReturningWork(new ReturningWork<Integer>() {

                    @Override
                    public Integer execute(Connection connection) throws SQLException {
                        PreparedStatement preparedStatement = sessionImplementor.getJdbcCoordinator().getStatementPreparer().prepareStatement(updateSql);
                        try {
                            int index = 1;
                            // set REVEND = ?
                            final Number revisionNumber = audEntitiesCfg.getEnversService().getRevisionInfoNumberReader().getRevisionNumber(revision);
                            revisionInfoIdType.nullSafeSet(preparedStatement, revisionNumber, index, sessionImplementor);
                            index += revisionInfoIdType.getColumnSpan(sessionImplementor.getFactory());
                            // set [, REVEND_TSTMP = ?]
                            if (isRevisionEndTimestampEnabled) {
                                final Object revEndTimestampObj = revisionTimestampGetter.get(revision);
                                final Date revisionEndTimestamp = convertRevEndTimestampToDate(revEndTimestampObj);
                                final Type revEndTsType = rootAuditedEntityQueryable.getPropertyType(audEntitiesCfg.getRevisionEndTimestampFieldName());
                                revEndTsType.nullSafeSet(preparedStatement, revisionEndTimestamp, index, sessionImplementor);
                                index += revEndTsType.getColumnSpan(sessionImplementor.getFactory());
                            }
                            // where (prod_ent_id) = ?
                            final Type idType = rootProductionEntityQueryable.getIdentifierType();
                            idType.nullSafeSet(preparedStatement, id, index, sessionImplementor);
                            index += idType.getColumnSpan(sessionImplementor.getFactory());
                            // where REV <> ?
                            final Type revType = rootAuditedEntityQueryable.getPropertyType(audEntitiesCfg.getRevisionNumberPath());
                            revType.nullSafeSet(preparedStatement, revisionNumber, index, sessionImplementor);
                            return sessionImplementor.getJdbcCoordinator().getResultSetReturn().executeUpdate(preparedStatement);
                        } finally {
                            sessionImplementor.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(preparedStatement);
                            sessionImplementor.getJdbcCoordinator().afterStatementExecution();
                        }
                    }
                });
                if (rowCount != 1 && (!reuseEntityIdentifier || (getRevisionType(audEntitiesCfg, data) != RevisionType.ADD))) {
                    throw new RuntimeException("Cannot update previous revision for entity " + auditedEntityName + " and id " + id);
                }
            }
        });
    }
    sessionCacheCleaner.scheduleAuditDataRemoval(session, data);
}
Also used : BeforeTransactionCompletionProcess(org.hibernate.action.spi.BeforeTransactionCompletionProcess) Queryable(org.hibernate.persister.entity.Queryable) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Update(org.hibernate.sql.Update) Date(java.util.Date) ReturningWork(org.hibernate.jdbc.ReturningWork) CollectionType(org.hibernate.type.CollectionType) ComponentType(org.hibernate.type.ComponentType) MaterializedNClobType(org.hibernate.type.MaterializedNClobType) MaterializedClobType(org.hibernate.type.MaterializedClobType) MapType(org.hibernate.type.MapType) RevisionType(org.hibernate.envers.RevisionType) Type(org.hibernate.type.Type) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) UnionSubclassEntityPersister(org.hibernate.persister.entity.UnionSubclassEntityPersister)

Aggregations

SessionImplementor (org.hibernate.engine.spi.SessionImplementor)82 Session (org.hibernate.Session)59 Test (org.junit.Test)54 Connection (java.sql.Connection)20 TestForIssue (org.hibernate.testing.TestForIssue)18 PreparedStatement (java.sql.PreparedStatement)17 Work (org.hibernate.jdbc.Work)13 Statement (java.sql.Statement)12 List (java.util.List)12 Transaction (org.hibernate.Transaction)12 EntityPersister (org.hibernate.persister.entity.EntityPersister)12 ResultSet (java.sql.ResultSet)11 SQLException (java.sql.SQLException)11 ArrayList (java.util.ArrayList)7 JDBCException (org.hibernate.JDBCException)6 CollectionEntry (org.hibernate.engine.spi.CollectionEntry)6 EntityEntry (org.hibernate.engine.spi.EntityEntry)6 QueryParameters (org.hibernate.engine.spi.QueryParameters)6 ResultSetProcessor (org.hibernate.loader.plan.exec.process.spi.ResultSetProcessor)6 NamedParameterContext (org.hibernate.loader.plan.exec.query.spi.NamedParameterContext)6