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;
 import java.util.Map;

Represents a prepared batch statement. That is, a sql statement compiled as a prepared statement, and then executed multiple times in a single batch. This is, generally, a very efficient way to execute large numbers of the same statement where the statement only varies by the arguments bound to it.
 
 public class PreparedBatch extends SQLStatement<PreparedBatch>
 {
     private final List<PreparedBatchPartparts = new ArrayList<PreparedBatchPart>();
     private Binding currentBinding;
 
     PreparedBatch(StatementLocator locator,
                   StatementRewriter rewriter,
                   Handle handle,
                   StatementBuilder statementBuilder,
                   String sql,
                   ConcreteStatementContext ctx,
                   SQLLog log,
                   TimingCollector timingCollector,
                   Collection<StatementCustomizerstatementCustomizers,
                   Foreman foreman,
                   ContainerFactoryRegistry containerFactoryRegistry)
     {
         super(new Binding(), locatorrewriterhandlestatementBuildersqlctxlogtimingCollectorstatementCustomizersforemancontainerFactoryRegistry);
         this. = new Binding();
     }

    
Specify a value on the statement context for this batch

Returns:
self
 
     public PreparedBatch define(String keyObject value)
     {
         getContext().setAttribute(keyvalue);
         return this;
     }

    
Adds all key/value pairs in the Map to the StatementContext.

Parameters:
values containing key/value pairs.
Returns:
this
 
     public PreparedBatch define(final Map<String, ? extends Objectvalues)
     {
         if (values != null) {
             for (Map.Entry<String, ? extends Objectentryvalues.entrySet())
             {
                 getContext().setAttribute(entry.getKey(), entry.getValue());
             }
         }
         return this;
     }

    
Execute the batch

Returns:
the number of rows modified or inserted per batch part.
 
     public int[] execute()
     {
         // short circuit empty batch
         if (.size() == 0) return new int[]{};
 
        PreparedBatchPart current = .get(0);
        final String my_sql ;
        try {
            my_sql = getStatementLocator().locate(getSql(), getContext());
        }
        catch (Exception e) {
            throw new UnableToCreateStatementException(String.format("Exception while locating statement for [%s]",
                                                                     getSql()), egetContext());
        }
        final RewrittenStatement rewritten = getRewriter().rewrite(my_sqlcurrent.getParameters(), getContext());
        PreparedStatement stmt = null;
        try {
            try {
                stmt = getHandle().getConnection().prepareStatement(rewritten.getSql());
                addCleanable(Cleanables.forStatement(stmt));
            }
            catch (SQLException e) {
                throw new UnableToCreateStatementException(egetContext());
            }
            try {
                for (PreparedBatchPart part : ) {
                    rewritten.bind(part.getParameters(), stmt);
                    stmt.addBatch();
                }
            }
            catch (SQLException e) {
                throw new UnableToExecuteStatementException("Exception while binding parameters"egetContext());
            }
            beforeExecution(stmt);
            try {
                final long start = System.nanoTime();
                final int[] rs =  stmt.executeBatch();
                final long elapsedTime = (System.nanoTime() - start);
                getLog().logPreparedBatch(elapsedTime / 1000000L, rewritten.getSql(), .size());
                getTimingCollector().collect(elapsedTimegetContext());
                afterExecution(stmt);
                return rs;
            }
            catch (SQLException e) {
                throw new UnableToExecuteStatementException(egetContext());
            }
        }
        finally {
            try {
                cleanup();
            }
            finally {
                this..clear();
            }
        }
    }

    
Add a statement (part) to this batch. You'll need to bindBinaryStream any arguments to the part.

Returns:
A part which can be used to bindBinaryStream parts to the statement
    public PreparedBatchPart add()
    {
        PreparedBatchPart part = new PreparedBatchPart(this.,
                                                       this,
                                                       getStatementLocator(),
                                                       getRewriter(),
                                                       getHandle(),
                                                       getStatementBuilder(),
                                                       getSql(),
                                                       getConcreteContext(),
                                                       getLog(),
                                                       getTimingCollector(),
                                                       getForeman(),
                                                       getContainerMapperRegistry());
        .add(part);
        this. = new Binding();
        return part;
    }
	public PreparedBatch add(Object... args)
	{
        PreparedBatchPart part = add();
		for (int i = 0; i < args.length; ++i) {
			part.bind(iargs[i]);
		}
		return this;
	}


    
Create a new batch part by binding values looked up in args to named parameters on the statement.

Parameters:
args map to bind arguments from for named parameters on the statement
Returns:
the new batch part
    public PreparedBatchPart add(Map<String, ? extends Objectargs)
    {
        PreparedBatchPart part = add();
        part.bindFromMap(args);
        return part;
    }

    
The number of statements which are in this batch
    public int getSize()
    {
        return .size();
    }

    
The number of statements which are in this batch
    public int size()
    {
        return .size();
    }
    @Override
    protected Binding getParams()
    {
        return this.;
    }
New to GrepCode? Check out our FAQ X