com.j256.ormlite.dao
Class BaseDaoImpl<T,ID>

java.lang.Object
  extended by com.j256.ormlite.dao.BaseDaoImpl<T,ID>
All Implemented Interfaces:
CloseableIterable<T>, Dao<T,ID>, Iterable<T>

public abstract class BaseDaoImpl<T,ID>
extends Object
implements Dao<T,ID>

Base class for the Database Access Objects that handle the reading and writing a class from the database.

This class is also Iterable which means you can do a for (T obj : dao) type of loop code to iterate through the table of persisted objects. See iterator().

NOTE: If you are using the Spring type wiring, initialize() should be called after all of the set methods. In Spring XML, init-method="initialize" should be used.

Author:
graywatson

Nested Class Summary
 
Nested classes/interfaces inherited from interface com.j256.ormlite.dao.Dao
Dao.CreateOrUpdateStatus
 
Field Summary
protected  ConnectionSource connectionSource
           
protected  DatabaseType databaseType
           
protected  Class<T> dataClass
           
protected  CloseableIterator<T> lastIterator
           
protected  StatementExecutor<T,ID> statementExecutor
           
protected  DatabaseTableConfig<T> tableConfig
           
protected  TableInfo<T,ID> tableInfo
           
 
Constructor Summary
protected BaseDaoImpl(Class<T> dataClass)
          Construct our base DAO using Spring type wiring.
protected BaseDaoImpl(ConnectionSource connectionSource, Class<T> dataClass)
          Construct our base DAO class.
protected BaseDaoImpl(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)
          Construct our base DAO class.
 
Method Summary
<CT> CT
callBatchTasks(Callable<CT> callable)
          Call the call-able that will perform a number of batch tasks.
protected  void checkForInitialized()
           
 void clearObjectCache()
          Flush the object cache if it has been enabled.
 CloseableIterator<T> closeableIterator()
          Returns an iterator over a set of elements of type T which can be closed.
 void closeLastIterator()
          This closes the last iterator returned by the Dao.iterator() method.
 long countOf()
          Returns the number of rows in the table associated with the data class.
 long countOf(PreparedQuery<T> preparedQuery)
          Returns the number of rows in the table associated with the prepared query passed in.
 int create(T data)
          Create a new row in the database from an object.
static
<T,ID> Dao<T,ID>
createDao(ConnectionSource connectionSource, Class<T> clazz)
          Deprecated. You should be using the DaoManager.createDao(ConnectionSource, Class)
static
<T,ID> Dao<T,ID>
createDao(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig)
          Deprecated. You should be using the DaoManager.createDao(ConnectionSource, DatabaseTableConfig)
 T createIfNotExists(T data)
          This is a convenience method to creating a data item but only if the ID does not already exist in the table.
 Dao.CreateOrUpdateStatus createOrUpdate(T data)
          This is a convenience method for creating an item in the database if it does not exist.
 int delete(Collection<T> datas)
          Delete a collection of objects from the database using an IN SQL clause.
 int delete(PreparedDelete<T> preparedDelete)
          Delete the objects that match the prepared statement argument.
 int delete(T data)
          Delete an object from the database.
 DeleteBuilder<T,ID> deleteBuilder()
          Like Dao.queryBuilder() but allows you to build an DELETE statement.
 int deleteById(ID id)
          Delete an object from the database that has an id.
 int deleteIds(Collection<ID> ids)
          Delete the objects that match the collection of ids from the database using an IN SQL clause.
 int executeRaw(String statement, String... arguments)
          Run a raw execute SQL statement to the database.The arguments are optional but can be set with strings to expand ? type of SQL.
 ID extractId(T data)
          Returns the ID from the data argument passed in.
 FieldType findForeignFieldType(Class<?> clazz)
          Returns the class of the DAO.
 Class<T> getDataClass()
          Returns the class of the DAO.
<FT> ForeignCollection<FT>
getEmptyForeignCollection(String fieldName)
          Returns an empty collection that can be assigned to a collection field.
 ObjectCache getObjectCache()
          Returns the current object-cache being used by the DAO or null if none.
 GenericRowMapper<T> getSelectStarRowMapper()
          Return a row mapper that is suitable for mapping results from a query to select * (star).
 DatabaseTableConfig<T> getTableConfig()
          Returns the table configuration information associated with the Dao's class or null if none.
 TableInfo<T,ID> getTableInfo()
          Used by internal classes to get the table information structure for the Dao's class.
 CloseableWrappedIterable<T> getWrappedIterable()
          This makes a one time use iterable class that can be closed afterwards.
 CloseableWrappedIterable<T> getWrappedIterable(PreparedQuery<T> preparedQuery)
          Same as Dao.getWrappedIterable() but with a prepared query parameter.
 boolean idExists(ID id)
          Returns true if an object exists that matches this ID otherwise false.
 void initialize()
          Initialize the various DAO configurations after the various setters have been called.
 boolean isTableExists()
          Returns true if the table already exists otherwise false.
 boolean isUpdatable()
          Returns true if we can call update on this class.
 CloseableIterator<T> iterator()
          This satisfies the Iterable interface for the class and allows you to iterate through the objects in the table using SQL.
 CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery)
          Same as Dao.iterator() but with a prepared query parameter.
 T mapSelectStarRow(DatabaseResults results)
          Return the latest row from the database results from a query to select * (star).
 boolean objectsEqual(T data1, T data2)
          Return true if the two arguments are equal.
 String objectToString(T data)
          Return the string version of the object with each of the known field values shown.
 List<T> query(PreparedQuery<T> preparedQuery)
          Query for the items in the object table which match the prepared query.
 QueryBuilder<T,ID> queryBuilder()
          Create and return a new query builder object which allows you to build a custom SELECT statement.
 List<T> queryForAll()
          Query for all of the items in the object table.
 List<T> queryForEq(String fieldName, Object value)
          Query for the items in the object table that match a simple where with a single field = value type of WHERE clause.
 List<T> queryForFieldValues(Map<String,Object> fieldValues)
          Query for the rows in the database that matches all of the field to value entries from the map passed in.
 List<T> queryForFieldValuesArgs(Map<String,Object> fieldValues)
          Same as Dao.queryForFieldValues(Map) but this uses SelectArg and SQL ? arguments.
 T queryForFirst(PreparedQuery<T> preparedQuery)
          Query for and return the first item in the object table which matches the PreparedQuery.
 T queryForId(ID id)
          Retrieves an object associated with a specific ID.
 List<T> queryForMatching(T matchObj)
          Query for the rows in the database that match the object passed in as an argument.
 List<T> queryForMatchingArgs(T matchObj)
          Same as Dao.queryForMatching(Object) but this uses SelectArg and SQL ? arguments.
 T queryForSameId(T data)
          Query for a data item in the table that has the same ID as the data parameter.
 GenericRawResults<Object[]> queryRaw(String query, DataType[] columnTypes, String... arguments)
          Similar to the Dao.queryRaw(String, String...) but instead of an array of String results being returned by the iterator, this uses the column-types parameter to return an array of Objects instead.
<GR> GenericRawResults<GR>
queryRaw(String query, RawRowMapper<GR> mapper, String... arguments)
          Similar to the Dao.queryRaw(String, String...) but this iterator returns rows that you can map yourself.
 GenericRawResults<String[]> queryRaw(String query, String... arguments)
          Similar to the Dao.iterator(PreparedQuery) except it returns a GenericRawResults object associated with the SQL select query argument.
 int refresh(T data)
          Does a query for the object's id and copies in each of the field values from the database to refresh the data parameter.
 CloseableIterator<T> seperateIterator()
          Same as iterator() except this doesn't set the last iterator which can be closed with the closeLastIterator().
 CloseableIterator<T> seperateIterator(PreparedQuery<T> preparedQuery)
          Same as iterator(PreparedQuery) except this doesn't set the last iterator which can be closed with the closeLastIterator().
 void setConnectionSource(ConnectionSource connectionSource)
           
 void setObjectCache(boolean enabled)
          Call this with true to enable an object cache for the DAO.
 void setObjectCache(ObjectCache objectCache)
          Same as Dao.setObjectCache(boolean) except you specify the actual cache instance to use for the DAO.
 void setTableConfig(DatabaseTableConfig<T> tableConfig)
          Used if you want to configure the class for the Dao by hand or with spring instead of using the DatabaseField annotation in the class.
 int update(PreparedUpdate<T> preparedUpdate)
          Update all rows in the table according to the prepared statement argument.
 int update(T data)
          Save the fields from an object to the database.
 UpdateBuilder<T,ID> updateBuilder()
          Like Dao.queryBuilder() but allows you to build an UPDATE statement.
 int updateId(T data, ID newId)
          Update an object in the database to change its id to the newId parameter.
 int updateRaw(String statement, String... arguments)
          Run a raw update SQL statement to the database.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

statementExecutor

protected StatementExecutor<T,ID> statementExecutor

databaseType

protected DatabaseType databaseType

dataClass

protected final Class<T> dataClass

tableConfig

protected DatabaseTableConfig<T> tableConfig

tableInfo

protected TableInfo<T,ID> tableInfo

connectionSource

protected ConnectionSource connectionSource

lastIterator

protected CloseableIterator<T> lastIterator
Constructor Detail

BaseDaoImpl

protected BaseDaoImpl(Class<T> dataClass)
               throws SQLException
Construct our base DAO using Spring type wiring. The ConnectionSource must be set with the setConnectionSource(com.j256.ormlite.support.ConnectionSource) method afterwards and then the initialize() method must be called. The dataClass provided must have its fields marked with DatabaseField annotations or the setTableConfig(com.j256.ormlite.table.DatabaseTableConfig) method must be called before the initialize() method is called.

If you are using Spring then your should use: init-method="initialize"

Parameters:
dataClass - Class associated with this Dao. This must match the T class parameter.
Throws:
SQLException

BaseDaoImpl

protected BaseDaoImpl(ConnectionSource connectionSource,
                      Class<T> dataClass)
               throws SQLException
Construct our base DAO class. The dataClass provided must have its fields marked with DatabaseField or javax.persistance annotations.

Parameters:
connectionSource - Source of our database connections.
dataClass - Class associated with this Dao. This must match the T class parameter.
Throws:
SQLException

BaseDaoImpl

protected BaseDaoImpl(ConnectionSource connectionSource,
                      DatabaseTableConfig<T> tableConfig)
               throws SQLException
Construct our base DAO class.

Parameters:
connectionSource - Source of our database connections.
tableConfig - Hand or Spring wired table configuration information.
Throws:
SQLException
Method Detail

initialize

public void initialize()
                throws SQLException
Initialize the various DAO configurations after the various setters have been called.

Throws:
SQLException

queryForId

public T queryForId(ID id)
             throws SQLException
Description copied from interface: Dao
Retrieves an object associated with a specific ID.

Specified by:
queryForId in interface Dao<T,ID>
Parameters:
id - Identifier that matches a specific row in the database to find and return.
Returns:
The object that has the ID field which equals id or null if no matches.
Throws:
SQLException - on any SQL problems or if more than 1 item with the id are found in the database.

queryForFirst

public T queryForFirst(PreparedQuery<T> preparedQuery)
                throws SQLException
Description copied from interface: Dao
Query for and return the first item in the object table which matches the PreparedQuery. See Dao.queryBuilder() for more information. This can be used to return the object that matches a single unique column. You should use Dao.queryForId(Object) if you want to query for the id column.

Specified by:
queryForFirst in interface Dao<T,ID>
Parameters:
preparedQuery - Query used to match the objects in the database.
Returns:
The first object that matches the query.
Throws:
SQLException - on any SQL problems.

queryForAll

public List<T> queryForAll()
                    throws SQLException
Description copied from interface: Dao
Query for all of the items in the object table. For medium sized or large tables, this may load a lot of objects into memory so you should consider using the Dao.iterator() method instead.

Specified by:
queryForAll in interface Dao<T,ID>
Returns:
A list of all of the objects in the table.
Throws:
SQLException - on any SQL problems.

queryForEq

public List<T> queryForEq(String fieldName,
                          Object value)
                   throws SQLException
Description copied from interface: Dao
Query for the items in the object table that match a simple where with a single field = value type of WHERE clause. This is a convenience method for calling queryBuilder().where().eq(fieldName, value).query().

Specified by:
queryForEq in interface Dao<T,ID>
Returns:
A list of the objects in the table that match the fieldName = value;
Throws:
SQLException - on any SQL problems.

queryBuilder

public QueryBuilder<T,ID> queryBuilder()
Description copied from interface: Dao
Create and return a new query builder object which allows you to build a custom SELECT statement. You call methods on the builder to construct your statement and then call QueryBuilder.prepare() once you are ready to build. This returns a PreparedQuery object which gets passed to Dao.query(PreparedQuery) or Dao.iterator(PreparedQuery).

Specified by:
queryBuilder in interface Dao<T,ID>

updateBuilder

public UpdateBuilder<T,ID> updateBuilder()
Description copied from interface: Dao
Like Dao.queryBuilder() but allows you to build an UPDATE statement. You can then call call UpdateBuilder.prepare() and pass the returned PreparedUpdate to Dao.update(PreparedUpdate).

Specified by:
updateBuilder in interface Dao<T,ID>

deleteBuilder

public DeleteBuilder<T,ID> deleteBuilder()
Description copied from interface: Dao
Like Dao.queryBuilder() but allows you to build an DELETE statement. You can then call call DeleteBuilder.prepare() and pass the returned PreparedDelete to Dao.delete(PreparedDelete).

Specified by:
deleteBuilder in interface Dao<T,ID>

query

public List<T> query(PreparedQuery<T> preparedQuery)
              throws SQLException
Description copied from interface: Dao
Query for the items in the object table which match the prepared query. See Dao.queryBuilder() for more information.

NOTE: For medium sized or large tables, this may load a lot of objects into memory so you should consider using the Dao.iterator(PreparedQuery) method instead.

Specified by:
query in interface Dao<T,ID>
Parameters:
preparedQuery - Query used to match the objects in the database.
Returns:
A list of all of the objects in the table that match the query.
Throws:
SQLException - on any SQL problems.

queryForMatching

public List<T> queryForMatching(T matchObj)
                         throws SQLException
Description copied from interface: Dao
Query for the rows in the database that match the object passed in as an argument. Any fields in the matching object that are not the default value (null, false, 0, 0.0, etc.) are used as the matching parameters with AND. If you are worried about SQL quote escaping, you should use Dao.queryForMatchingArgs(Object).

Specified by:
queryForMatching in interface Dao<T,ID>
Throws:
SQLException

queryForMatchingArgs

public List<T> queryForMatchingArgs(T matchObj)
                             throws SQLException
Description copied from interface: Dao
Same as Dao.queryForMatching(Object) but this uses SelectArg and SQL ? arguments. This is slightly more expensive but you don't have to worry about SQL quote escaping.

Specified by:
queryForMatchingArgs in interface Dao<T,ID>
Throws:
SQLException

queryForFieldValues

public List<T> queryForFieldValues(Map<String,Object> fieldValues)
                            throws SQLException
Description copied from interface: Dao
Query for the rows in the database that matches all of the field to value entries from the map passed in. If you are worried about SQL quote escaping, you should use Dao.queryForFieldValuesArgs(Map).

Specified by:
queryForFieldValues in interface Dao<T,ID>
Throws:
SQLException

queryForFieldValuesArgs

public List<T> queryForFieldValuesArgs(Map<String,Object> fieldValues)
                                throws SQLException
Description copied from interface: Dao
Same as Dao.queryForFieldValues(Map) but this uses SelectArg and SQL ? arguments. This is slightly more expensive but you don't have to worry about SQL quote escaping.

Specified by:
queryForFieldValuesArgs in interface Dao<T,ID>
Throws:
SQLException

queryForSameId

public T queryForSameId(T data)
                 throws SQLException
Description copied from interface: Dao
Query for a data item in the table that has the same ID as the data parameter.

Specified by:
queryForSameId in interface Dao<T,ID>
Throws:
SQLException

create

public int create(T data)
           throws SQLException
Description copied from interface: Dao
Create a new row in the database from an object.

Specified by:
create in interface Dao<T,ID>
Parameters:
data - The data item that we are creating in the database.
Returns:
The number of rows updated in the database. This should be 1.
Throws:
SQLException

createIfNotExists

public T createIfNotExists(T data)
                    throws SQLException
Description copied from interface: Dao
This is a convenience method to creating a data item but only if the ID does not already exist in the table. This extracts the ID from the data parameter, does a Dao.queryForId(Object) on it, returning the data if it exists. If it does not exist Dao.create(Object) will be called with the parameter.

Specified by:
createIfNotExists in interface Dao<T,ID>
Returns:
Either the data parameter if it was inserted or the data that existed already in the database.
Throws:
SQLException

createOrUpdate

public Dao.CreateOrUpdateStatus createOrUpdate(T data)
                                        throws SQLException
Description copied from interface: Dao
This is a convenience method for creating an item in the database if it does not exist. If it does exist then all of the fields will be updated from the fields in the parameter object.

Specified by:
createOrUpdate in interface Dao<T,ID>
Returns:
Status object with the number of rows changed and whether an insert or update was performed.
Throws:
SQLException

update

public int update(T data)
           throws SQLException
Description copied from interface: Dao
Save the fields from an object to the database. If you have made changes to an object, this is how you persist those changes to the database. You cannot use this method to update the id field -- see Dao.updateId(T, ID).

Specified by:
update in interface Dao<T,ID>
Parameters:
data - The data item that we are updating in the database.
Returns:
The number of rows updated in the database. This should be 1.
Throws:
SQLException - on any SQL problems.

updateId

public int updateId(T data,
                    ID newId)
             throws SQLException
Description copied from interface: Dao
Update an object in the database to change its id to the newId parameter. The data must have its current id set. If the id field has already changed then it cannot be updated. After the id has been updated in the database, the id field of the data object will also be changed.

NOTE: Depending on the database type and the id type, you may be unable to change the id of the field.

Specified by:
updateId in interface Dao<T,ID>
Parameters:
data - The data item that we are updating in the database with the current id.
newId - The new id that you want to update the data with.
Returns:
The number of rows updated in the database. This should be 1.
Throws:
SQLException - on any SQL problems.

update

public int update(PreparedUpdate<T> preparedUpdate)
           throws SQLException
Description copied from interface: Dao
Update all rows in the table according to the prepared statement argument. To use this, the UpdateBuilder must have set-columns applied to it using the UpdateBuilder.updateColumnValue(String, Object) or UpdateBuilder.updateColumnExpression(String, String) methods.

Specified by:
update in interface Dao<T,ID>
Parameters:
preparedUpdate - A prepared statement to match database rows to be deleted and define the columns to update.
Returns:
The number of rows updated in the database.
Throws:
SQLException - on any SQL problems.

refresh

public int refresh(T data)
            throws SQLException
Description copied from interface: Dao
Does a query for the object's id and copies in each of the field values from the database to refresh the data parameter. Any local object changes to persisted fields will be overwritten. If the database has been updated this brings your local object up to date.

Specified by:
refresh in interface Dao<T,ID>
Parameters:
data - The data item that we are refreshing with fields from the database.
Returns:
The number of rows found in the database that correspond to the data id. This should be 1.
Throws:
SQLException - on any SQL problems or if the data item is not found in the table or if more than 1 item is found with data's id.

delete

public int delete(T data)
           throws SQLException
Description copied from interface: Dao
Delete an object from the database.

Specified by:
delete in interface Dao<T,ID>
Parameters:
data - The data item that we are deleting from the database.
Returns:
The number of rows updated in the database. This should be 1.
Throws:
SQLException - on any SQL problems.

deleteById

public int deleteById(ID id)
               throws SQLException
Description copied from interface: Dao
Delete an object from the database that has an id.

Specified by:
deleteById in interface Dao<T,ID>
Parameters:
id - The id of the item that we are deleting from the database.
Returns:
The number of rows updated in the database. This should be 1.
Throws:
SQLException - on any SQL problems.

delete

public int delete(Collection<T> datas)
           throws SQLException
Description copied from interface: Dao
Delete a collection of objects from the database using an IN SQL clause.

Specified by:
delete in interface Dao<T,ID>
Parameters:
datas - A collection of data items to be deleted.
Returns:
The number of rows updated in the database. This should be the size() of the collection.
Throws:
SQLException - on any SQL problems.

deleteIds

public int deleteIds(Collection<ID> ids)
              throws SQLException
Description copied from interface: Dao
Delete the objects that match the collection of ids from the database using an IN SQL clause.

Specified by:
deleteIds in interface Dao<T,ID>
Parameters:
ids - A collection of data ids to be deleted.
Returns:
The number of rows updated in the database. This should be the size() of the collection.
Throws:
SQLException - on any SQL problems.

delete

public int delete(PreparedDelete<T> preparedDelete)
           throws SQLException
Description copied from interface: Dao
Delete the objects that match the prepared statement argument.

Specified by:
delete in interface Dao<T,ID>
Parameters:
preparedDelete - A prepared statement to match database rows to be deleted.
Returns:
The number of rows updated in the database.
Throws:
SQLException - on any SQL problems.

iterator

public CloseableIterator<T> iterator()
Description copied from interface: Dao
This satisfies the Iterable interface for the class and allows you to iterate through the objects in the table using SQL. You can use code similar to the following:

 for (Account account : accountDao) { ... }
 

WARNING: because the Iterator.hasNext(), Iterator.next(), etc. methods can only throw RuntimeException, the code has to wrap any SQLException with IllegalStateException. Make sure to catch IllegalStateException and look for a SQLException cause.

WARNING: The underlying results object will only be closed if you page all the way to the end of the iterator using the for() loop or if you call CloseableIterator.close() directly. You can also call the Dao.closeLastIterator() if you are not iterating across this DAO in multiple threads.

Specified by:
iterator in interface Dao<T,ID>
Specified by:
iterator in interface Iterable<T>
Returns:
An iterator of the class that uses SQL to step across the database table.

closeableIterator

public CloseableIterator<T> closeableIterator()
Description copied from interface: CloseableIterable
Returns an iterator over a set of elements of type T which can be closed.

Specified by:
closeableIterator in interface CloseableIterable<T>

seperateIterator

public CloseableIterator<T> seperateIterator()
Same as iterator() except this doesn't set the last iterator which can be closed with the closeLastIterator().


getWrappedIterable

public CloseableWrappedIterable<T> getWrappedIterable()
Description copied from interface: Dao
This makes a one time use iterable class that can be closed afterwards. The DAO itself is CloseableWrappedIterable but multiple threads can each call this to get their own closeable iterable. This allows you to do something like:
 CloseableWrappedIterable wrappedIterable = fooDao.getWrappedIterable();
 try {
   for (Foo foo : wrappedIterable) {
       ...
   }
 } finally {
   wrappedIterable.close();
 }
 

Specified by:
getWrappedIterable in interface Dao<T,ID>

getWrappedIterable

public CloseableWrappedIterable<T> getWrappedIterable(PreparedQuery<T> preparedQuery)
Description copied from interface: Dao
Same as Dao.getWrappedIterable() but with a prepared query parameter. See Dao.queryBuilder() or Dao.iterator(PreparedQuery) for more information.

Specified by:
getWrappedIterable in interface Dao<T,ID>

closeLastIterator

public void closeLastIterator()
                       throws SQLException
Description copied from interface: Dao
This closes the last iterator returned by the Dao.iterator() method.

NOTE: This is not reentrant. If multiple threads are getting iterators from this DAO then you should use the Dao.getWrappedIterable() method to get a wrapped iterable for each thread instead.

Specified by:
closeLastIterator in interface Dao<T,ID>
Throws:
SQLException

iterator

public CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery)
                              throws SQLException
Description copied from interface: Dao
Same as Dao.iterator() but with a prepared query parameter. See Dao.queryBuilder() for more information. You use it like the following:

 QueryBuilder<Account, String> qb = accountDao.queryBuilder();
 ... custom query builder methods
 CloseableIterator<Account> iterator = partialDao.iterator(qb.prepare());
 try {
     while (iterator.hasNext()) {
         Account account = iterator.next();
         ...
     }
 } finish {
     iterator.close();
 }
 

Specified by:
iterator in interface Dao<T,ID>
Parameters:
preparedQuery - Query used to iterate across a sub-set of the items in the database.
Returns:
An iterator for T.
Throws:
SQLException - on any SQL problems.

seperateIterator

public CloseableIterator<T> seperateIterator(PreparedQuery<T> preparedQuery)
                                      throws SQLException
Same as iterator(PreparedQuery) except this doesn't set the last iterator which can be closed with the closeLastIterator().

Throws:
SQLException

queryRaw

public GenericRawResults<String[]> queryRaw(String query,
                                            String... arguments)
                                     throws SQLException
Description copied from interface: Dao
Similar to the Dao.iterator(PreparedQuery) except it returns a GenericRawResults object associated with the SQL select query argument. Although you should use the Dao.iterator() for most queries, this method allows you to do special queries that aren't supported otherwise. Like the above iterator methods, you must call close on the returned RawResults object once you are done with it. The arguments are optional but can be set with strings to expand ? type of SQL.

You can use the StatementBuilder.prepareStatementString() method here if you want to build the query using the structure of the QueryBuilder.

 QueryBuilder<Account, Integer> qb = accountDao.queryBuilder();
 qb.where().ge("orderCount", 10);
 results = accountDao.queryRaw(qb.prepareStatementString());
 

If you want to use the QueryBuilder with arguments to the raw query then you should do something like:

 QueryBuilder<Account, Integer> qb = accountDao.queryBuilder();
 // we specify a SelectArg here to generate a ? in the statement string below
 qb.where().ge("orderCount", new SelectArg());
 // the 10 at the end is an optional argument to fulfill the SelectArg above
 results = accountDao.queryRaw(qb.prepareStatementString(), rawRowMapper, 10);
 

Specified by:
queryRaw in interface Dao<T,ID>
Throws:
SQLException

queryRaw

public <GR> GenericRawResults<GR> queryRaw(String query,
                                           RawRowMapper<GR> mapper,
                                           String... arguments)
                               throws SQLException
Description copied from interface: Dao
Similar to the Dao.queryRaw(String, String...) but this iterator returns rows that you can map yourself. For every result that is returned by the database, the RawRowMapper.mapRow(String[], String[]) method is called so you can convert the result columns into an object to be returned by the iterator. The arguments are optional but can be set with strings to expand ? type of SQL.

Specified by:
queryRaw in interface Dao<T,ID>
Throws:
SQLException

queryRaw

public GenericRawResults<Object[]> queryRaw(String query,
                                            DataType[] columnTypes,
                                            String... arguments)
                                     throws SQLException
Description copied from interface: Dao
Similar to the Dao.queryRaw(String, String...) but instead of an array of String results being returned by the iterator, this uses the column-types parameter to return an array of Objects instead. The arguments are optional but can be set with strings to expand ? type of SQL.

Specified by:
queryRaw in interface Dao<T,ID>
Throws:
SQLException

executeRaw

public int executeRaw(String statement,
                      String... arguments)
               throws SQLException
Description copied from interface: Dao
Run a raw execute SQL statement to the database.The arguments are optional but can be set with strings to expand ? type of SQL.

Specified by:
executeRaw in interface Dao<T,ID>
Returns:
number of rows affected.
Throws:
SQLException

updateRaw

public int updateRaw(String statement,
                     String... arguments)
              throws SQLException
Description copied from interface: Dao
Run a raw update SQL statement to the database. The statement must be an SQL INSERT, UPDATE or DELETE statement.The arguments are optional but can be set with strings to expand ? type of SQL.

Specified by:
updateRaw in interface Dao<T,ID>
Returns:
number of rows affected.
Throws:
SQLException

callBatchTasks

public <CT> CT callBatchTasks(Callable<CT> callable)
                  throws Exception
Description copied from interface: Dao
Call the call-able that will perform a number of batch tasks. This is for performance when you want to run a number of database operations at once -- maybe loading data from a file. This will turn off what databases call "auto-commit" mode, run the call-able and then re-enable "auto-commit". If auto-commit is not supported then a transaction will be used instead.

NOTE: If neither auto-commit nor transactions are supported by the database type then this may just call the callable.

Specified by:
callBatchTasks in interface Dao<T,ID>
Throws:
Exception

objectToString

public String objectToString(T data)
Description copied from interface: Dao
Return the string version of the object with each of the known field values shown. Useful for testing and debugging.

Specified by:
objectToString in interface Dao<T,ID>
Parameters:
data - The data item for which we are returning the toString information.

objectsEqual

public boolean objectsEqual(T data1,
                            T data2)
                     throws SQLException
Description copied from interface: Dao
Return true if the two arguments are equal. This checks each of the fields defined in the database to see if they are equal. Useful for testing and debugging.

Specified by:
objectsEqual in interface Dao<T,ID>
Parameters:
data1 - One of the data items that we are checking for equality.
data2 - The other data item that we are checking for equality.
Throws:
SQLException

extractId

public ID extractId(T data)
             throws SQLException
Description copied from interface: Dao
Returns the ID from the data argument passed in. This is used by some of the internal queries to be able to search by id.

Specified by:
extractId in interface Dao<T,ID>
Throws:
SQLException

getDataClass

public Class<T> getDataClass()
Description copied from interface: Dao
Returns the class of the DAO. This is used by internal query operators.

Specified by:
getDataClass in interface Dao<T,ID>

findForeignFieldType

public FieldType findForeignFieldType(Class<?> clazz)
Description copied from interface: Dao
Returns the class of the DAO. This is used by internal query operators.

Specified by:
findForeignFieldType in interface Dao<T,ID>

isUpdatable

public boolean isUpdatable()
Description copied from interface: Dao
Returns true if we can call update on this class. This is used most likely by folks who are extending the base dao classes.

Specified by:
isUpdatable in interface Dao<T,ID>

isTableExists

public boolean isTableExists()
                      throws SQLException
Description copied from interface: Dao
Returns true if the table already exists otherwise false. This is not supported on Android.

Specified by:
isTableExists in interface Dao<T,ID>
Throws:
SQLException

countOf

public long countOf()
             throws SQLException
Description copied from interface: Dao
Returns the number of rows in the table associated with the data class. Depending on the size of the table and the database type, this may be expensive and take a while.

Specified by:
countOf in interface Dao<T,ID>
Throws:
SQLException

countOf

public long countOf(PreparedQuery<T> preparedQuery)
             throws SQLException
Description copied from interface: Dao
Returns the number of rows in the table associated with the prepared query passed in. Depending on the size of the table and the database type, this may be expensive and take a while.

Specified by:
countOf in interface Dao<T,ID>
Throws:
SQLException

getEmptyForeignCollection

public <FT> ForeignCollection<FT> getEmptyForeignCollection(String fieldName)
                                                throws SQLException
Description copied from interface: Dao
Returns an empty collection that can be assigned to a collection field. This allows you to add things to the collection from the start. For example let's say you have an Account which has the field:
 @ForeignCollectionField(columnName = "orders")
 Collection<Order> orders;
 
You would then call:
 account.orders = accoundDao.getEmptyForeignCollection("orders");
 // this would add it the collection and the internal DAO
 account.orders.add(order1);
 

Specified by:
getEmptyForeignCollection in interface Dao<T,ID>
Parameters:
fieldName - parameter is the field name of the foreign collection field -- you might consider using the ForeignCollectionField.columnName() to set the name to a static name.
Throws:
SQLException

setObjectCache

public void setObjectCache(boolean enabled)
                    throws SQLException
Description copied from interface: Dao
Call this with true to enable an object cache for the DAO. Set to false to disable any caching. It is (as of 9/2011) one of the newer features of ORMLite. It keeps a ReferenceObjectCache of the objects (using WeakReference) referenced by the DAO. No support for objects returned by the Dao.queryRaw(java.lang.String, java.lang.String...) methods.

Specified by:
setObjectCache in interface Dao<T,ID>
Throws:
SQLException - If the DAO's class does not have an id field which is required by the ObjectCache.

setObjectCache

public void setObjectCache(ObjectCache objectCache)
                    throws SQLException
Description copied from interface: Dao
Same as Dao.setObjectCache(boolean) except you specify the actual cache instance to use for the DAO. This allows you to use a ReferenceObjectCache with SoftReference setting, the LruObjectCache, or inject your own cache implementation. Call it with null to disable the cache.

Specified by:
setObjectCache in interface Dao<T,ID>
Throws:
SQLException - If the DAO's class does not have an id field which is required by the ObjectCache.

getObjectCache

public ObjectCache getObjectCache()
Description copied from interface: Dao
Returns the current object-cache being used by the DAO or null if none.

Specified by:
getObjectCache in interface Dao<T,ID>

clearObjectCache

public void clearObjectCache()
Description copied from interface: Dao
Flush the object cache if it has been enabled. This will remove an objects that are in the cache to reclaim memory. Any future queries will re-request them from the database.

Specified by:
clearObjectCache in interface Dao<T,ID>

mapSelectStarRow

public T mapSelectStarRow(DatabaseResults results)
                   throws SQLException
Description copied from interface: Dao
Return the latest row from the database results from a query to select * (star).

Specified by:
mapSelectStarRow in interface Dao<T,ID>
Throws:
SQLException

getSelectStarRowMapper

public GenericRowMapper<T> getSelectStarRowMapper()
                                           throws SQLException
Description copied from interface: Dao
Return a row mapper that is suitable for mapping results from a query to select * (star).

Specified by:
getSelectStarRowMapper in interface Dao<T,ID>
Throws:
SQLException

idExists

public boolean idExists(ID id)
                 throws SQLException
Description copied from interface: Dao
Returns true if an object exists that matches this ID otherwise false.

Specified by:
idExists in interface Dao<T,ID>
Throws:
SQLException

getTableConfig

public DatabaseTableConfig<T> getTableConfig()
Returns the table configuration information associated with the Dao's class or null if none.


getTableInfo

public TableInfo<T,ID> getTableInfo()
Used by internal classes to get the table information structure for the Dao's class.


setConnectionSource

public void setConnectionSource(ConnectionSource connectionSource)

setTableConfig

public void setTableConfig(DatabaseTableConfig<T> tableConfig)
Used if you want to configure the class for the Dao by hand or with spring instead of using the DatabaseField annotation in the class. This must be called before initialize().


createDao

@Deprecated
public static <T,ID> Dao<T,ID> createDao(ConnectionSource connectionSource,
                                                    Class<T> clazz)
                           throws SQLException
Deprecated. You should be using the DaoManager.createDao(ConnectionSource, Class)

Helper method to create a Dao object without having to define a class. Dao classes are supposed to be convenient but if you have a lot of classes, they can seem to be a pain.

NOTE: You should use DaoManager.createDao(ConnectionSource, DatabaseTableConfig) instead of this method so you won't have to create the DAO multiple times.

Throws:
SQLException

createDao

@Deprecated
public static <T,ID> Dao<T,ID> createDao(ConnectionSource connectionSource,
                                                    DatabaseTableConfig<T> tableConfig)
                           throws SQLException
Deprecated. You should be using the DaoManager.createDao(ConnectionSource, DatabaseTableConfig)

Helper method to create a Dao object used by some internal methods that already have the TableInfo.

NOTE: You should use DaoManager.createDao(ConnectionSource, DatabaseTableConfig) instead of this method so you won't have to create the DAO multiple times.

Throws:
SQLException

checkForInitialized

protected void checkForInitialized()


This content is licensed by Gray Watson under the Creative Commons Attribution-Share Alike 3.0 License.