Search in sources :

Example 16 with QueryParameters

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

the class EntityWithNonLazyCollectionResultSetProcessorTest method testEntityWithSet.

@Test
public void testEntityWithSet() throws Exception {
    final EntityPersister entityPersister = sessionFactory().getEntityPersister(Person.class.getName());
    // create some test data
    Session session = openSession();
    session.beginTransaction();
    Person person = new Person();
    person.id = 1;
    person.name = "John Doe";
    person.nickNames.add("Jack");
    person.nickNames.add("Johnny");
    session.save(person);
    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 {
                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(2, results.size());
        Object result1 = results.get(0);
        assertSame(result1, results.get(1));
        assertNotNull(result1);
        Person workPerson = ExtraAssertions.assertTyping(Person.class, result1);
        assertEquals(1, workPerson.id.intValue());
        assertEquals(person.name, workPerson.name);
        assertTrue(Hibernate.isInitialized(workPerson.nickNames));
        assertEquals(2, workPerson.nickNames.size());
        assertEquals(person.nickNames, workPerson.nickNames);
        workSession.getTransaction().commit();
        workSession.close();
    }
    // clean up test data
    session = openSession();
    session.beginTransaction();
    session.delete(person);
    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 17 with QueryParameters

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

the class EntityWithNonLazyOneToManySetResultSetProcessorTest method testEntityWithSet.

@Test
public void testEntityWithSet() throws Exception {
    final EntityPersister entityPersister = sessionFactory().getEntityPersister(Poster.class.getName());
    // create some test data
    Session session = openSession();
    session.beginTransaction();
    Poster poster = new Poster();
    poster.pid = 0;
    poster.name = "John Doe";
    Message message1 = new Message();
    message1.mid = 1;
    message1.msgTxt = "Howdy!";
    message1.poster = poster;
    poster.messages.add(message1);
    Message message2 = new Message();
    message2.mid = 2;
    message2.msgTxt = "Bye!";
    message2.poster = poster;
    poster.messages.add(message2);
    session.save(poster);
    session.getTransaction().commit();
    session.close();
    session = openSession();
    session.beginTransaction();
    Poster posterGotten = (Poster) session.get(Poster.class, poster.pid);
    assertEquals(0, posterGotten.pid.intValue());
    assertEquals(poster.name, posterGotten.name);
    assertTrue(Hibernate.isInitialized(posterGotten.messages));
    assertEquals(2, posterGotten.messages.size());
    for (Message message : posterGotten.messages) {
        if (message.mid == 1) {
            assertEquals(message1.msgTxt, message.msgTxt);
        } else if (message.mid == 2) {
            assertEquals(message2.msgTxt, message.msgTxt);
        } else {
            fail("unexpected message id.");
        }
        assertSame(posterGotten, message.poster);
    }
    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 {
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setInt(1, 0);
                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(2, results.size());
        Object result1 = results.get(0);
        assertNotNull(result1);
        assertSame(result1, results.get(1));
        Poster workPoster = ExtraAssertions.assertTyping(Poster.class, result1);
        assertEquals(0, workPoster.pid.intValue());
        assertEquals(poster.name, workPoster.name);
        assertTrue(Hibernate.isInitialized(workPoster.messages));
        assertEquals(2, workPoster.messages.size());
        assertTrue(Hibernate.isInitialized(posterGotten.messages));
        assertEquals(2, workPoster.messages.size());
        for (Message message : workPoster.messages) {
            if (message.mid == 1) {
                assertEquals(message1.msgTxt, message.msgTxt);
            } else if (message.mid == 2) {
                assertEquals(message2.msgTxt, message.msgTxt);
            } else {
                fail("unexpected message id.");
            }
            assertSame(workPoster, message.poster);
        }
        workSession.getTransaction().commit();
        workSession.close();
    }
    // clean up test data
    session = openSession();
    session.beginTransaction();
    session.delete(poster);
    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 18 with QueryParameters

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

the class NonEncapsulatedCompositeIdResultSetProcessorTest method testCompositeIdWithKeyManyToOne.

@Test
public void testCompositeIdWithKeyManyToOne() throws Exception {
    final String personId = "John Doe";
    Person p = new Person();
    p.setName(personId);
    final Address a = new Address();
    a.setPerson(p);
    p.setAddress(a);
    a.setType("HOME");
    a.setStreet("Main St");
    a.setState("Sweet Home Alabama");
    a.setZip("3181");
    Session s = openSession();
    Transaction t = s.beginTransaction();
    s.persist(p);
    t.commit();
    s.close();
    final EntityPersister personPersister = sessionFactory().getEntityPersister(Person.class.getName());
    final EntityPersister addressPersister = sessionFactory().getEntityPersister(Address.class.getName());
    {
        final List results = getResults(addressPersister, new Callback() {

            @Override
            public void bind(PreparedStatement ps) throws SQLException {
                ps.setString(1, personId);
                ps.setString(2, "HOME");
            }

            @Override
            public QueryParameters getQueryParameters() {
                QueryParameters qp = new QueryParameters();
                qp.setPositionalParameterTypes(new Type[] { addressPersister.getIdentifierType() });
                qp.setPositionalParameterValues(new Object[] { a });
                qp.setOptionalObject(a);
                qp.setOptionalEntityName(addressPersister.getEntityName());
                qp.setOptionalId(a);
                qp.setLockOptions(LockOptions.NONE);
                return qp;
            }
        });
        assertEquals(1, results.size());
        Object result = results.get(0);
        assertNotNull(result);
    }
    // test loading the Person (the entity with normal id def, but mixed composite fk to Address)
    {
        final List results = getResults(personPersister, new Callback() {

            @Override
            public void bind(PreparedStatement ps) throws SQLException {
                ps.setString(1, personId);
            }

            @Override
            public QueryParameters getQueryParameters() {
                QueryParameters qp = new QueryParameters();
                qp.setPositionalParameterTypes(new Type[] { personPersister.getIdentifierType() });
                qp.setPositionalParameterValues(new Object[] { personId });
                qp.setOptionalObject(null);
                qp.setOptionalEntityName(personPersister.getEntityName());
                qp.setOptionalId(personId);
                qp.setLockOptions(LockOptions.NONE);
                return qp;
            }
        });
        assertEquals(1, results.size());
        Object result = results.get(0);
        assertNotNull(result);
    }
    //		CardField cardFieldWork = ExtraAssertions.assertTyping( CardField.class, result );
    //		assertEquals( cardFieldGotten, cardFieldWork );
    // clean up test data
    s = openSession();
    s.beginTransaction();
    s.createQuery("delete Address").executeUpdate();
    s.createQuery("delete Person").executeUpdate();
    s.getTransaction().commit();
    s.close();
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Address(org.hibernate.test.onetoone.formula.Address) Transaction(org.hibernate.Transaction) PreparedStatement(java.sql.PreparedStatement) ArrayList(java.util.ArrayList) List(java.util.List) QueryParameters(org.hibernate.engine.spi.QueryParameters) Person(org.hibernate.test.onetoone.formula.Person) Session(org.hibernate.Session) Test(org.junit.Test)

Example 19 with QueryParameters

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

the class HQLQueryPlan method performList.

/**
	 * Coordinates the efforts to perform a list across all the included query translators.
	 *
	 * @param queryParameters The query parameters
	 * @param session The session
	 *
	 * @return The query result list
	 *
	 * @throws HibernateException Indicates a problem performing the query
	 */
@SuppressWarnings("unchecked")
public List performList(QueryParameters queryParameters, SharedSessionContractImplementor session) throws HibernateException {
    if (traceEnabled) {
        LOG.tracev("Find: {0}", getSourceQuery());
        queryParameters.traceParameters(session.getFactory());
    }
    final RowSelection rowSelection = queryParameters.getRowSelection();
    final boolean hasLimit = rowSelection != null && rowSelection.definesLimits();
    final boolean needsLimit = hasLimit && translators.length > 1;
    final QueryParameters queryParametersToUse;
    if (needsLimit) {
        LOG.needsLimit();
        final RowSelection selection = new RowSelection();
        selection.setFetchSize(queryParameters.getRowSelection().getFetchSize());
        selection.setTimeout(queryParameters.getRowSelection().getTimeout());
        queryParametersToUse = queryParameters.createCopyUsing(selection);
    } else {
        queryParametersToUse = queryParameters;
    }
    //fast path to avoid unnecessary allocation and copying
    if (translators.length == 1) {
        return translators[0].list(session, queryParametersToUse);
    }
    final int guessedResultSize = guessResultSize(rowSelection);
    final List combinedResults = new ArrayList(guessedResultSize);
    final IdentitySet distinction;
    if (needsLimit) {
        distinction = new IdentitySet(guessedResultSize);
    } else {
        distinction = null;
    }
    int includedCount = -1;
    translator_loop: for (QueryTranslator translator : translators) {
        final List tmp = translator.list(session, queryParametersToUse);
        if (needsLimit) {
            // NOTE : firstRow is zero-based
            final int first = queryParameters.getRowSelection().getFirstRow() == null ? 0 : queryParameters.getRowSelection().getFirstRow();
            final int max = queryParameters.getRowSelection().getMaxRows() == null ? -1 : queryParameters.getRowSelection().getMaxRows();
            for (final Object result : tmp) {
                if (!distinction.add(result)) {
                    continue;
                }
                includedCount++;
                if (includedCount < first) {
                    continue;
                }
                combinedResults.add(result);
                if (max >= 0 && includedCount > max) {
                    // break the outer loop !!!
                    break translator_loop;
                }
            }
        } else {
            combinedResults.addAll(tmp);
        }
    }
    return combinedResults;
}
Also used : IdentitySet(org.hibernate.internal.util.collections.IdentitySet) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) QueryParameters(org.hibernate.engine.spi.QueryParameters) RowSelection(org.hibernate.engine.spi.RowSelection) QueryTranslator(org.hibernate.hql.spi.QueryTranslator)

Example 20 with QueryParameters

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

the class Loader method loadCollectionSubselect.

/**
	 * Called by subclasses that batch initialize collections
	 */
protected final void loadCollectionSubselect(final SharedSessionContractImplementor session, final Serializable[] ids, final Object[] parameterValues, final Type[] parameterTypes, final Map<String, TypedValue> namedParameters, final Type type) throws HibernateException {
    final Type[] idTypes = new Type[ids.length];
    Arrays.fill(idTypes, type);
    try {
        doQueryAndInitializeNonLazyCollections(session, new QueryParameters(parameterTypes, parameterValues, namedParameters, ids), true);
    } catch (SQLException sqle) {
        throw factory.getJdbcServices().getSqlExceptionHelper().convert(sqle, "could not load collection by subselect: " + MessageHelper.collectionInfoString(getCollectionPersisters()[0], ids, getFactory()), getSQLString());
    }
}
Also used : EntityType(org.hibernate.type.EntityType) VersionType(org.hibernate.type.VersionType) AssociationType(org.hibernate.type.AssociationType) Type(org.hibernate.type.Type) SQLException(java.sql.SQLException) QueryParameters(org.hibernate.engine.spi.QueryParameters)

Aggregations

QueryParameters (org.hibernate.engine.spi.QueryParameters)35 List (java.util.List)20 ArrayList (java.util.ArrayList)17 SQLException (java.sql.SQLException)14 PreparedStatement (java.sql.PreparedStatement)10 Session (org.hibernate.Session)10 Type (org.hibernate.type.Type)10 Test (org.junit.Test)9 EntityPersister (org.hibernate.persister.entity.EntityPersister)8 Connection (java.sql.Connection)7 ResultSet (java.sql.ResultSet)7 Work (org.hibernate.jdbc.Work)7 ResultSetProcessor (org.hibernate.loader.plan.exec.process.spi.ResultSetProcessor)7 NamedParameterContext (org.hibernate.loader.plan.exec.query.spi.NamedParameterContext)7 LoadQueryDetails (org.hibernate.loader.plan.exec.spi.LoadQueryDetails)7 LoadPlan (org.hibernate.loader.plan.spi.LoadPlan)7 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)6 AssociationType (org.hibernate.type.AssociationType)5 Serializable (java.io.Serializable)4 EntityType (org.hibernate.type.EntityType)4