Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2004 - 2011 Brian McCallister
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.skife.jdbi.v2;
 
 
 import java.util.List;
Statement providing convenience result handling for SQL queries.
 
 public class Query<ResultType> extends SQLStatement<Query<ResultType>> implements ResultBearing<ResultType>
 {
     private final ResultSetMapper<ResultType> mapper;
     private final MappingRegistry             mappingRegistry;
 
     Query(Binding params,
           ResultSetMapper<ResultType> mapper,
           StatementLocator locator,
           StatementRewriter statementRewriter,
           Handle handle,
           StatementBuilder cache,
           String sql,
           ConcreteStatementContext ctx,
           SQLLog log,
           TimingCollector timingCollector,
           Collection<StatementCustomizercustomizers,
           MappingRegistry mappingRegistry,
           Foreman foreman,
           ContainerFactoryRegistry containerFactoryRegistry)
     {
         super(paramslocatorstatementRewriterhandlecachesqlctxlogtimingCollectorcustomizersforemancontainerFactoryRegistry);
         this. = mapper;
         this. = new MappingRegistry(mappingRegistry);
     }

    
Executes the select

Will eagerly load all results

Throws:
org.skife.jdbi.v2.exceptions.UnableToCreateStatementException if there is an error creating the statement
org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException if there is an error executing the statement
org.skife.jdbi.v2.exceptions.ResultSetException if there is an error dealing with the result set
 
     public List<ResultType> list()
     {
         return list(List.class);
     }
 
     public <ContainerType> ContainerType list(Class<ContainerType> containerType)
     {
         ContainerBuilder<ContainerType> builder = getContainerMapperRegistry().createBuilderFor(containerType);
         return fold(buildernew Folder3<ContainerBuilder<ContainerType>, ResultType>()
         {
             public ContainerBuilder<ContainerType> fold(ContainerBuilder<ContainerType> accumulator,
                                                         ResultType rs,
                                                         FoldController ctl,
                                                         StatementContext ctxthrows SQLException
             {
                 accumulator.add(rs);
                 return accumulator;
             }
         }).build();
     }

    
Executes the select

Will eagerly load all results up to a maximum of maxRows

Parameters:
maxRows The maximum number of results to include in the result, any rows in the result set beyond this number will be ignored.
Throws:
org.skife.jdbi.v2.exceptions.UnableToCreateStatementException if there is an error creating the statement
org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException if there is an error executing the statement
org.skife.jdbi.v2.exceptions.ResultSetException if there is an error dealing with the result set
    public List<ResultType> list(final int maxRows)
    {
        try {
            return this.internalExecute(new QueryResultSetMunger<List<ResultType>>(this)
            {
                public List<ResultType> munge(ResultSet rsthrows SQLException
                {
                    List<ResultType> result_list = new ArrayList<ResultType>();
                    int index = 0;
                    while (rs.next() && index < maxRows) {
                        result_list.add(.map(index++, rsgetContext()));
                    }
                    return result_list;
                }
            });
        }
        finally {
            cleanup();
        }
    }

    
Used to execute the query and traverse the result set with a accumulator. Folding over the result involves invoking a callback for each row, passing into the callback the return value from the previous function invocation.

Parameters:
accumulator The initial accumulator value
folder Defines the function which will fold over the result set.
Returns:
The return value from the last invocation of Folder.fold(java.lang.Object,java.sql.ResultSet)
See also:
Folder
    public <AccumulatorType> AccumulatorType fold(AccumulatorType accumulatorfinal Folder2<AccumulatorType> folder)
    {
        final AtomicReference<AccumulatorType> acc = new AtomicReference<AccumulatorType>(accumulator);
        try {
            this.internalExecute(new QueryResultSetMunger<Void>(this)
            {
                public Void munge(ResultSet rsthrows SQLException
                {
                    while (rs.next()) {
                        acc.set(folder.fold(acc.get(), rsgetContext()));
                    }
                    return null;
                }
            });
            return acc.get();
        }
        finally {
            cleanup();
        }
    }
    public <AccumulatorType> AccumulatorType fold(final AccumulatorType accumulator,
                                                  final Folder3<AccumulatorType, ResultType> folder)
    {
        try {
            return this.internalExecute(new QueryResultSetMunger<AccumulatorType>(this)
            {
                private int idx = 0;
                private AccumulatorType ac = accumulator;
                @Override
                protected AccumulatorType munge(ResultSet rsthrows SQLException
                {
                    final FoldController ctl = new FoldController(rs);
                    while (!ctl.isAborted() && rs.next()) {
                        ResultType row_value = .map(++, rsgetContext());
                        this. = folder.fold(row_valuectlgetContext());
                    }
                    return ;
                }
            });
        }
        finally {
            cleanup();
        }
    }


    
Used to execute the query and traverse the result set with a accumulator. Folding over the result involves invoking a callback for each row, passing into the callback the return value from the previous function invocation.

Deprecated:
Use fold(java.lang.Object,org.skife.jdbi.v2.Folder2)
Parameters:
accumulator The initial accumulator value
folder Defines the function which will fold over the result set.
Returns:
The return value from the last invocation of Folder.fold(java.lang.Object,java.sql.ResultSet)
See also:
Folder
    public <AccumulatorType> AccumulatorType fold(AccumulatorType accumulatorfinal Folder<AccumulatorType> folder)
    {
        final AtomicReference<AccumulatorType> acc = new AtomicReference<AccumulatorType>(accumulator);
        try {
            this.internalExecute(new QueryResultSetMunger<Void>(this)
            {
                public Void munge(ResultSet rsthrows SQLException
                {
                    while (rs.next()) {
                        acc.set(folder.fold(acc.get(), rs));
                    }
                    return null;
                }
            });
            return acc.get();
        }
        finally {
            cleanup();
        }
    }

    
Obtain a forward-only result set iterator. Note that you must explicitely close the iterator to close the underlying resources.
    public ResultIterator<ResultType> iterator()
    {
        return this.internalExecute(new QueryResultMunger<ResultIterator<ResultType>>()
        {
            public ResultIterator<ResultType> munge(Statement stmtthrows SQLException
            {
                return new ResultSetResultIterator<ResultType>(,
                                                               Query.this,
                                                               stmt,
                                                               getContext());
            }
        });
    }

    
Executes the select.

Specifies a maximum of one result on the JDBC statement, and map that one result as the return value, or return null if there is nothing in the results

Returns:
first result, mapped, or null if there is no first result
    public ResultType first()
    {
        return (ResultType) first(UnwrappedSingleValue.class);
    }
    public <T> T first(Class<T> containerType)
    {
        ContainerBuilder builder = getContainerMapperRegistry().createBuilderFor(containerType);
        return (T) this.fold(buildernew Folder3<ContainerBuilder, ResultType>()
        {
            public ContainerBuilder fold(ContainerBuilder accumulator, ResultType rsFoldController controlStatementContext ctxthrows SQLException
            {
                accumulator.add(rs);
                control.abort();
                return accumulator;
            }
        }).build();
    }

    
Provide basic JavaBean mapping capabilities. Will instantiate an instance of resultType for each row and set the JavaBean properties which match fields in the result set.

Parameters:
resultType JavaBean class to map result set fields into the properties of, by name
Returns:
a Query which provides the bean property mapping
    public <Type> Query<Type> map(Class<Type> resultType)
    {
        return this.map(new BeanMapper<Type>(resultType));
    }

    
Makes use of registered mappers to map the result set to the desired type.

    public <T> Query<T> mapTo(Class<T> resultType)
    {
        return this.map(new RegisteredMapper(resultType));
    }
    public <T> Query<T> map(ResultSetMapper<T> mapper)
    {
        return new Query<T>(getParameters(),
                            mapper,
                            getStatementLocator(),
                            getRewriter(),
                            getHandle(),
                            getStatementBuilder(),
                            getSql(),
                            getConcreteContext(),
                            getLog(),
                            getTimingCollector(),
                            getStatementCustomizers(),
                            new MappingRegistry(),
                            getForeman().createChild(),
                            getContainerMapperRegistry().createChild());
    }

    
Specify the fetch size for the query. This should cause the results to be fetched from the underlying RDBMS in groups of rows equal to the number passed. This is useful for doing chunked streaming of results when exhausting memory could be a problem.

Parameters:
i the number of rows to fetch in a bunch
Returns:
the modified query
    public Query<ResultType> setFetchSize(final int fetchSize)
    {
        return this;
    }

    
Specify the maimum number of rows the query is to return. This uses the underlying JDBC java.sql.Statement.setMaxRows(int)}.

Parameters:
i maximum number of rows to return
Returns:
modified query
    public Query<ResultType> setMaxRows(final int maxRows)
    {
        return this;
    }

    
Specify the maimum field size in the result set. This uses the underlying JDBC java.sql.Statement.setMaxFieldSize(int)

Parameters:
i maximum field size
Returns:
modified query
    public Query<ResultType> setMaxFieldSize(final int maxFields)
    {
        return this;
    }

    
Specify that the fetch order should be reversed, uses the underlying java.sql.Statement.setFetchDirection(int)

Returns:
the modified query
    public Query<ResultType> fetchReverse()
    {
        return this;
    }

    
Specify that the fetch order should be forward, uses the underlying java.sql.Statement.setFetchDirection(int)

Returns:
the modified query
    public Query<ResultType> fetchForward()
    {
        return this;
    }
    public void registerMapper(ResultSetMapper m)
    {
        this..add(new InferredMapperFactory(m));
    }
    public void registerMapper(ResultSetMapperFactory m)
    {
        this..add(m);
    }
New to GrepCode? Check out our FAQ X