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.Map;
This class provides the access point for jDBI. Use it to obtain Handle instances and provide "global" configuration for all handles obtained from it.
 
 public class DBI implements IDBI
 {
     private final Map<StringObjectglobalStatementAttributes = new ConcurrentHashMap<StringObject>();
     private final MappingRegistry mappingRegistry = new MappingRegistry();
     private final Foreman foreman = new Foreman();
 
     private final ConnectionFactory connectionFactory;
 
     private AtomicReference<SQLLoglog = new AtomicReference<SQLLog>(new NoOpLog());
Constructor for use with a DataSource which will provide

Parameters:
dataSource
 
     public DBI(DataSource dataSource)
     {
         this(new DataSourceConnectionFactory(dataSource));
         assert (dataSource != null);
     }

    
Constructor used to allow for obtaining a Connection in a customized manner.

The org.skife.jdbi.v2.tweak.ConnectionFactory.openConnection() method will be invoked to obtain a connection instance whenever a Handle is opened.

Parameters:
connectionFactory PrvidesJDBC connections to Handle instances
 
     public DBI(ConnectionFactory connectionFactory)
     {
         assert (connectionFactory != null);
         this. = connectionFactory;
     }

    
Create a DBI which directly uses the DriverManager

Parameters:
url JDBC URL for connections
 
     public DBI(final String url)
     {
         this(new ConnectionFactory()
         {
             public Connection openConnection() throws SQLException
            {
                return DriverManager.getConnection(url);
            }
        });
    }

    
Create a DBI which directly uses the DriverManager

Parameters:
url JDBC URL for connections
props Properties to pass to DriverManager.getConnection(url, props) for each new handle
    public DBI(final String urlfinal Properties props)
    {
        this(new ConnectionFactory()
        {
            public Connection openConnection() throws SQLException
            {
                return DriverManager.getConnection(urlprops);
            }
        });
    }

    
Create a DBI which directly uses the DriverManager

Parameters:
url JDBC URL for connections
username User name for connection authentication
password Password for connection authentication
    public DBI(final String urlfinal String usernamefinal String password)
    {
        this(new ConnectionFactory()
        {
            public Connection openConnection() throws SQLException
            {
                return DriverManager.getConnection(urlusernamepassword);
            }
        });
    }

    
Use a non-standard StatementLocator to look up named statements for all handles created from this DBi instance.

Parameters:
locator StatementLocator which will be used by all Handle instances created from this DBI
    public void setStatementLocator(StatementLocator locator)
    {
        assert (locator != null);
        this..set(locator);
    }
    {
        return this..get();
    }

    
Use a non-standard StatementRewriter to transform SQL for all Handle instances created by this DBI.

Parameters:
rewriter StatementRewriter to use on all Handle instances
    public void setStatementRewriter(StatementRewriter rewriter)
    {
        assert (rewriter != null);
        this..set(rewriter);
    }
    {
        return this..get();
    }

    
Specify the TransactionHandler instance to use. This allows overriding transaction semantics, or mapping into different transaction management systems.

The default version uses local transactions on the database Connection instances obtained.

Parameters:
handler The TransactionHandler to use for all Handle instances obtained from this DBI
    public void setTransactionHandler(TransactionHandler handler)
    {
        assert (handler != null);
        this..set(handler);
    }
    {
        return this..get();
    }

    
Obtain a Handle to the data source wrapped by this DBI instance

Returns:
an open Handle instance
    public Handle open()
    {
        try {
            final long start = System.nanoTime();
            Connection conn = .openConnection();
            final long stop = System.nanoTime();
            StatementBuilder cache = .get().createStatementBuilder(conn);
            Handle h = new BasicHandle(.get(),
                                       .get(),
                                       cache,
                                       .get(),
                                       conn,
                                       ,
                                       .get(),
                                       .get(),
                                       new MappingRegistry(),
                                       .createChild(),
                                       .createChild());
            .get().logObtainHandle((stop - start) / 1000000L, h);
            return h;
        }
        catch (SQLException e) {
            throw new UnableToObtainConnectionException(e);
        }
    }

    
Register a result set mapper which will have its parameterized type inspected to determine what it maps to Will be used with Query.mapTo(java.lang.Class) for registered mappings.
    public void registerMapper(ResultSetMapper mapper) {
        .add(mapper);
    }

    
Register a result set mapper factory. Will be used with Query.mapTo(java.lang.Class) for registerd mappings.
    public void registerMapper(ResultSetMapperFactory factory) {
        .add(factory);
    }

    
Define an attribute on every StatementContext for every statement created from a handle obtained from this DBI instance.

Parameters:
key The key for the attribute
value the value for the attribute
    public void define(String keyObject value)
    {
        this..put(keyvalue);
    }

    
A convenience function which manages the lifecycle of a handle and yields it to a callback for use by clients.

Parameters:
callback A callback which will receive an open Handle
Returns:
the value returned by callback
Throws:
org.skife.jdbi.v2.exceptions.CallbackFailedException Will be thrown if callback raises an exception. This exception will wrap the exception thrown by the callback.
    public <ReturnType> ReturnType withHandle(HandleCallback<ReturnType> callbackthrows CallbackFailedException
    {
        final Handle h = this.open();
        try {
            return callback.withHandle(h);
        }
        catch (Exception e) {
            throw new CallbackFailedException(e);
        }
        finally {
            h.close();
        }
    }

    
A convenience function which manages the lifecycle of a handle and yields it to a callback for use by clients. The handle will be in a transaction when the callback is invoked, and that transaction will be committed if the callback finishes normally, or rolled back if the callback raises an exception.

Parameters:
callback A callback which will receive an open Handle, in a transaction
Returns:
the value returned by callback
Throws:
org.skife.jdbi.v2.exceptions.CallbackFailedException Will be thrown if callback raises an exception. This exception will wrap the exception thrown by the callback.
    public <ReturnType> ReturnType inTransaction(final TransactionCallback<ReturnType> callbackthrows CallbackFailedException
    {
        return withHandle(new HandleCallback<ReturnType>() {
            public ReturnType withHandle(Handle handlethrows Exception
            {
                return handle.inTransaction(callback);
            }
        });
    }
    public <ReturnType> ReturnType inTransaction(final TransactionIsolationLevel isolationfinal TransactionCallback<ReturnType> callbackthrows CallbackFailedException
    {
        return withHandle(new HandleCallback<ReturnType>() {
            public ReturnType withHandle(Handle handlethrows Exception
            {
                return handle.inTransaction(isolationcallback);
            }
        });
    }

    
Open a handle and attach a new sql object of the specified type to that handle. Be sure to close the sql object (via a close() method, or calling IDBI.close(java.lang.Object)

Parameters:
sqlObjectType an interface with annotations declaring desired behavior
<SqlObjectType>
Returns:
a new sql object of the specified type, with a dedicated handle
    public <SqlObjectType> SqlObjectType open(Class<SqlObjectType> sqlObjectType)
    {
        return SqlObjectBuilder.open(thissqlObjectType);
    }

    
Create a new sql object which will obtain and release connections from this dbi instance, as it needs to, and can, respectively. You should not explicitely close this sql object

Parameters:
sqlObjectType an interface with annotations declaring desired behavior
<SqlObjectType>
Returns:
a new sql object of the specified type, with a dedicated handle
    public <SqlObjectType> SqlObjectType onDemand(Class<SqlObjectType> sqlObjectType)
    {
        return SqlObjectBuilder.onDemand(thissqlObjectType);
    }

    
Used to close a sql object which lacks a close() method.

Parameters:
sqlObject the sql object to close
    public void close(Object sqlObject)
    {
        if (sqlObject instanceof Handle) {
            // just because someone is *sure* to do it
            Handle h = (HandlesqlObject;
            h.close();
        }
        else {
            SqlObjectBuilder.close(sqlObject);
        }
    }

    
Convenience methd used to obtain a handle from a specific data source

Parameters:
dataSource
Returns:
Handle using a Connection obtained from the provided DataSource
    public static Handle open(DataSource dataSource)
    {
        assert (dataSource != null);
        return new DBI(dataSource).open();
    }

    
Create a Handle wrapping a particular JDBC Connection

Parameters:
connection
Returns:
Handle bound to connection
    public static Handle open(final Connection connection)
    {
        assert (connection != null);
        return new DBI(new ConnectionFactory()
        {
            public Connection openConnection()
            {
                return connection;
            }
        }).open();
    }

    
Obtain a handle with just a JDBC URL

Parameters:
url JDBC Url
Returns:
newly opened Handle
    public static Handle open(final String url)
    {
        assert (url != null);
        return new DBI(url).open();
    }

    
Obtain a handle with just a JDBC URL

Parameters:
url JDBC Url
username JDBC username for authentication
password JDBC password for authentication
Returns:
newly opened Handle
    public static Handle open(final String urlfinal String usernamefinal String password)
    {
        assert (url != null);
        return new DBI(urlusernamepassword).open();
    }

    
Obtain a handle with just a JDBC URL

Parameters:
url JDBC Url
props JDBC properties
Returns:
newly opened Handle
    public static Handle open(final String urlfinal Properties props)
    {
        assert (url != null);
        return new DBI(urlprops).open();
    }

    
Allows customization of how prepared statements are created. When a Handle is created against this DBI instance the factory will be used to create a StatementBuilder for that specific handle. When the handle is closed, the StatementBuilder's close method will be invoked.
    {
        this..set(factory);
    }
    {
        return this..get();
    }

    
Specify the class used to log sql statements. Will be passed to all handles created from this instance
    public void setSQLLog(SQLLog log)
    {
        this..set(log);
    }
    public SQLLog getSQLLog()
    {
        return this..get();
    }

    
Add a callback to accumulate timing information about the queries running from this data source.
    public void setTimingCollector(final TimingCollector timingCollector) {
        if (timingCollector == null) {
        }
        else {
            this..set(timingCollector);
        }
    }
    {
        return this..get();
    }
    public void registerArgumentFactory(ArgumentFactory<?> argumentFactory)
    {
        .register(argumentFactory);
    }
    public void registerContainerFactory(ContainerFactory<?> factory)
    {
        this..register(factory);
    }
New to GrepCode? Check out our FAQ X