Search in sources :

Example 51 with SessionImplementor

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

the class SimpleResultSetProcessorTest method testSimpleEntityProcessing.

@Test
public void testSimpleEntityProcessing() throws Exception {
    final EntityPersister entityPersister = sessionFactory().getEntityPersister(SimpleEntity.class.getName());
    // create some test data
    Session session = openSession();
    session.beginTransaction();
    session.save(new SimpleEntity(1, "the only"));
    session.getTransaction().commit();
    session.close();
    {
        final LoadPlan plan = Helper.INSTANCE.buildLoadPlan(sessionFactory(), entityPersister);
        final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails(plan, sessionFactory());
        final String sql = queryDetails.getSqlStatement();
        final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
        final List results = new ArrayList();
        final Session workSession = openSession();
        workSession.beginTransaction();
        workSession.doWork(new Work() {

            @Override
            public void execute(Connection connection) throws SQLException {
                ((SessionImplementor) workSession).getFactory().getServiceRegistry().getService(JdbcServices.class).getSqlStatementLogger().logStatement(sql);
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setInt(1, 1);
                ResultSet resultSet = ps.executeQuery();
                results.addAll(resultSetProcessor.extractResults(resultSet, (SessionImplementor) workSession, new QueryParameters(), new NamedParameterContext() {

                    @Override
                    public int[] getNamedParameterLocations(String name) {
                        return new int[0];
                    }
                }, true, false, null, null));
                resultSet.close();
                ps.close();
            }
        });
        assertEquals(1, results.size());
        Object result = results.get(0);
        assertNotNull(result);
        SimpleEntity workEntity = ExtraAssertions.assertTyping(SimpleEntity.class, result);
        assertEquals(1, workEntity.id.intValue());
        assertEquals("the only", workEntity.name);
        workSession.getTransaction().commit();
        workSession.close();
    }
    // clean up test data
    session = openSession();
    session.beginTransaction();
    session.createQuery("delete SimpleEntity").executeUpdate();
    session.getTransaction().commit();
    session.close();
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) NamedParameterContext(org.hibernate.loader.plan.exec.query.spi.NamedParameterContext) ResultSetProcessor(org.hibernate.loader.plan.exec.process.spi.ResultSetProcessor) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) QueryParameters(org.hibernate.engine.spi.QueryParameters) LoadPlan(org.hibernate.loader.plan.spi.LoadPlan) LoadQueryDetails(org.hibernate.loader.plan.exec.spi.LoadQueryDetails) Work(org.hibernate.jdbc.Work) ResultSet(java.sql.ResultSet) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) ArrayList(java.util.ArrayList) List(java.util.List) Session(org.hibernate.Session) Test(org.junit.Test)

Example 52 with SessionImplementor

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

the class CriteriaQueryImpl method interpret.

@Override
public CriteriaInterpretation interpret(RenderingContext renderingContext) {
    final StringBuilder jpaqlBuffer = new StringBuilder();
    queryStructure.render(jpaqlBuffer, renderingContext);
    if (!getOrderList().isEmpty()) {
        jpaqlBuffer.append(" order by ");
        String sep = "";
        for (Order orderSpec : getOrderList()) {
            jpaqlBuffer.append(sep).append(((Renderable) orderSpec.getExpression()).render(renderingContext)).append(orderSpec.isAscending() ? " asc" : " desc");
            sep = ", ";
        }
    }
    final String jpaqlString = jpaqlBuffer.toString();
    log.debugf("Rendered criteria query -> %s", jpaqlString);
    return new CriteriaInterpretation() {

        @Override
        @SuppressWarnings("unchecked")
        public QueryImplementor buildCompiledQuery(SessionImplementor entityManager, final InterpretedParameterMetadata parameterMetadata) {
            final Map<String, Class> implicitParameterTypes = extractTypeMap(parameterMetadata.implicitParameterBindings());
            QueryImplementor<T> jpaqlQuery = entityManager.createQuery(jpaqlString, getResultType(), getSelection(), new HibernateEntityManagerImplementor.QueryOptions() {

                @Override
                public List<ValueHandlerFactory.ValueHandler> getValueHandlers() {
                    SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection();
                    return selection == null ? null : selection.getValueHandlers();
                }

                @Override
                public Map<String, Class> getNamedParameterExplicitTypes() {
                    return implicitParameterTypes;
                }

                @Override
                public ResultMetadataValidator getResultMetadataValidator() {
                    return new HibernateEntityManagerImplementor.QueryOptions.ResultMetadataValidator() {

                        @Override
                        public void validate(Type[] returnTypes) {
                            SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection();
                            if (selection != null) {
                                if (selection.isCompoundSelection()) {
                                    if (returnTypes.length != selection.getCompoundSelectionItems().size()) {
                                        throw new IllegalStateException("Number of return values [" + returnTypes.length + "] did not match expected [" + selection.getCompoundSelectionItems().size() + "]");
                                    }
                                } else {
                                    if (returnTypes.length > 1) {
                                        throw new IllegalStateException("Number of return values [" + returnTypes.length + "] did not match expected [1]");
                                    }
                                }
                            }
                        }
                    };
                }
            });
            for (ImplicitParameterBinding implicitParameterBinding : parameterMetadata.implicitParameterBindings()) {
                implicitParameterBinding.bind(jpaqlQuery);
            }
            return new CriteriaQueryTypeQueryAdapter(entityManager, jpaqlQuery, parameterMetadata.explicitParameterInfoMap());
        }

        private Map<String, Class> extractTypeMap(List<ImplicitParameterBinding> implicitParameterBindings) {
            final HashMap<String, Class> map = new HashMap<String, Class>();
            for (ImplicitParameterBinding implicitParameter : implicitParameterBindings) {
                map.put(implicitParameter.getParameterName(), implicitParameter.getJavaType());
            }
            return map;
        }
    };
}
Also used : HashMap(java.util.HashMap) CriteriaInterpretation(org.hibernate.query.criteria.internal.compile.CriteriaInterpretation) HibernateEntityManagerImplementor(org.hibernate.jpa.spi.HibernateEntityManagerImplementor) List(java.util.List) Order(javax.persistence.criteria.Order) InterpretedParameterMetadata(org.hibernate.query.criteria.internal.compile.InterpretedParameterMetadata) EntityType(javax.persistence.metamodel.EntityType) Type(org.hibernate.type.Type) CriteriaQueryTypeQueryAdapter(org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) HashMap(java.util.HashMap) Map(java.util.Map) ImplicitParameterBinding(org.hibernate.query.criteria.internal.compile.ImplicitParameterBinding)

Example 53 with SessionImplementor

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

the class MultipleSessionCollectionWarningTest method testUnsetSessionCannotOverwriteConnectedSesssion.

@Test
@TestForIssue(jiraKey = "HHH-9518")
public void testUnsetSessionCannotOverwriteConnectedSesssion() {
    Parent p = new Parent();
    Child c = new Child();
    p.children.add(c);
    Session s1 = openSession();
    s1.getTransaction().begin();
    s1.saveOrUpdate(p);
    // The collection is "connected" to s1 because it contains the CollectionEntry
    CollectionEntry ce = ((SessionImplementor) s1).getPersistenceContext().getCollectionEntry((PersistentCollection) p.children);
    assertNotNull(ce);
    // the collection session should be s1
    assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
    Session s2 = openSession();
    s2.getTransaction().begin();
    Triggerable triggerable = logInspection.watchForLogMessages("HHH000471:");
    assertFalse(triggerable.wasTriggered());
    // The following should trigger warning because we're unsetting a different session
    // We should not do this in practice; it is done here only to force the warning.
    // Since s1 was not flushed, the collection role will not be known (no way to test that).
    assertFalse(((PersistentCollection) p.children).unsetSession((SessionImplementor) s2));
    assertTrue(triggerable.wasTriggered());
    // collection's session should still be s1
    assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
    s2.getTransaction().rollback();
    s2.close();
    s1.getTransaction().rollback();
    s1.close();
}
Also used : CollectionEntry(org.hibernate.engine.spi.CollectionEntry) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) Triggerable(org.hibernate.testing.logger.Triggerable) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 54 with SessionImplementor

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

the class MultipleSessionCollectionWarningTest method testUnsetSessionCannotOverwriteConnectedSesssionFlushed.

@Test
@TestForIssue(jiraKey = "HHH-9518")
public void testUnsetSessionCannotOverwriteConnectedSesssionFlushed() {
    Parent p = new Parent();
    Child c = new Child();
    p.children.add(c);
    Session s1 = openSession();
    s1.getTransaction().begin();
    s1.saveOrUpdate(p);
    // flush the session so that p.children will contain its role
    s1.flush();
    // The collection is "connected" to s1 because it contains the CollectionEntry
    CollectionEntry ce = ((SessionImplementor) s1).getPersistenceContext().getCollectionEntry((PersistentCollection) p.children);
    assertNotNull(ce);
    // the collection session should be s1
    assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
    Session s2 = openSession();
    s2.getTransaction().begin();
    Triggerable triggerable = logInspection.watchForLogMessages("HHH000471:");
    assertFalse(triggerable.wasTriggered());
    // The following should trigger warning because we're unsetting a different session
    // We should not do this in practice; it is done here only to force the warning.
    // The collection role and key should be included in the message (no way to test that other than inspection).
    assertFalse(((PersistentCollection) p.children).unsetSession((SessionImplementor) s2));
    assertTrue(triggerable.wasTriggered());
    // collection's session should still be s1
    assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
    s2.getTransaction().rollback();
    s2.close();
    s1.getTransaction().rollback();
    s1.close();
}
Also used : CollectionEntry(org.hibernate.engine.spi.CollectionEntry) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) Triggerable(org.hibernate.testing.logger.Triggerable) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 55 with SessionImplementor

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

the class MultipleSessionCollectionWarningTest method testUnsetSessionCannotOverwriteNonConnectedSesssion.

@Test
@TestForIssue(jiraKey = "HHH-9518")
public void testUnsetSessionCannotOverwriteNonConnectedSesssion() {
    Parent p = new Parent();
    Child c = new Child();
    p.children.add(c);
    Session s1 = openSession();
    s1.getTransaction().begin();
    s1.saveOrUpdate(p);
    // Now remove the collection from the PersistenceContext without unsetting its session
    // This should never be done in practice; it is done here only to test that the warning
    // gets logged. s1 will not function properly so the transaction will ultimately need
    // to be rolled-back.
    CollectionEntry ce = (CollectionEntry) ((SessionImplementor) s1).getPersistenceContext().getCollectionEntries().remove(p.children);
    assertNotNull(ce);
    // the collection session should still be s1; the collection is no longer "connected" because its
    // CollectionEntry has been removed.
    assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
    Session s2 = openSession();
    s2.getTransaction().begin();
    Triggerable triggerable = logInspection.watchForLogMessages("HHH000471:");
    assertFalse(triggerable.wasTriggered());
    // The following should trigger warning because we're unsetting a different session.
    // We should not do this in practice; it is done here only to force the warning.
    // Since s1 was not flushed, the collection role will not be known (no way to test that).
    assertFalse(((PersistentCollection) p.children).unsetSession((SessionImplementor) s2));
    assertTrue(triggerable.wasTriggered());
    // collection's session should still be s1
    assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
    s2.getTransaction().rollback();
    s2.close();
    s1.getTransaction().rollback();
    s1.close();
}
Also used : CollectionEntry(org.hibernate.engine.spi.CollectionEntry) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) Triggerable(org.hibernate.testing.logger.Triggerable) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

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