com.j256.ormlite.dao
Interface Dao<T,ID>

Type Parameters:
T - The class that the code will be operating on.
ID - The class of the ID column associated with the class. The T class does not require an ID field. The class needs an ID parameter however so you can use Void or Object to satisfy the compiler.
All Superinterfaces:
CloseableIterable<T>, Iterable<T>
All Known Implementing Classes:
BaseDaoImpl

public interface Dao<T,ID>
extends CloseableIterable<T>

The definition of the Database Access Objects that handle the reading and writing a class from the database. Kudos to Robert A. for the general concept of this hierarchy.

Author:
graywatson

Nested Class Summary
static class Dao.CreateOrUpdateStatus
          Return class for the createOrUpdate(Object) method.
 
Method Summary
 void assignEmptyForeignCollection(T parent, String fieldName)
          Creates an empty collection and assigns it to the appropriate field in the parent object.
<CT> CT
callBatchTasks(Callable<CT> callable)
          Call the call-able that will perform a number of batch tasks.
 void clearObjectCache()
          Flush the object cache if it has been enabled.
 void closeLastIterator()
          This closes the last iterator returned by the iterator() method.
 void commit(DatabaseConnection connection)
          If you have previously set auto-commit to false using setAutoCommit(DatabaseConnection, boolean) then this will commit all changes to the database made from that point up to now on the connection returned by the startThreadConnection().
 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.
 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 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.
 void endThreadConnection(DatabaseConnection connection)
           WARNING: This method is for advanced users only.
 int executeRaw(String statement, String... arguments)
          Run a raw execute SQL statement to the database.
 int executeRawNoArgs(String statement)
          Run a raw execute SQL statement on the database without any arguments.
 ID extractId(T data)
          Returns the ID from the data argument passed in.
 FieldType findForeignFieldType(Class<?> clazz)
          Returns the class of the DAO.
 ConnectionSource getConnectionSource()
          Return the associated ConnectionSource or null if none set on the DAO yet.
 Class<T> getDataClass()
          Returns the class of the DAO.
<FT> ForeignCollection<FT>
getEmptyForeignCollection(String fieldName)
          Like assignEmptyForeignCollection(Object, String) but it returns the empty collection that you assign to the appropriate field.
 ObjectCache getObjectCache()
          Returns the current object-cache being used by the DAO or null if none.
 RawRowMapper<T> getRawRowMapper()
          Return a row mapper that is suitable for use with queryRaw(String, RawRowMapper, String...).
 GenericRowMapper<T> getSelectStarRowMapper()
          Return a row mapper that is suitable for mapping results from a query to select * (star).
 CloseableWrappedIterable<T> getWrappedIterable()
          This makes a one time use iterable class that can be closed afterwards.
 CloseableWrappedIterable<T> getWrappedIterable(PreparedQuery<T> preparedQuery)
          Same as getWrappedIterable() but with a prepared query parameter.
 boolean idExists(ID id)
          Returns true if an object exists that matches this ID otherwise false.
 boolean isAutoCommit()
          Deprecated. You should use the isAutoCommit(DatabaseConnection) method instead.
 boolean isAutoCommit(DatabaseConnection connection)
          Return true if the database connection returned by the startThreadConnection() is in auto-commit mode otherwise false.
 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(int resultFlags)
          Same as iterator() but while specifying flags for the results.
 CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery)
          Same as iterator() but with a prepared query parameter.
 CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery, int resultFlags)
          Same as iterator(PreparedQuery) but while specifying flags for the results.
 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 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 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 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.
<UO> GenericRawResults<UO>
queryRaw(String query, RawRowMapper<UO> mapper, String... arguments)
          Similar to the queryRaw(String, String...) but this iterator returns rows that you can map yourself.
 GenericRawResults<String[]> queryRaw(String query, String... arguments)
          Similar to the iterator(PreparedQuery) except it returns a GenericRawResults object associated with the SQL select query argument.
 long queryRawValue(String query, String... arguments)
          Perform a raw query that returns a single value (usually an aggregate function like MAX or COUNT).
 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.
 void rollBack(DatabaseConnection connection)
          If you have previously set auto-commit to false using setAutoCommit(DatabaseConnection, boolean) then this will roll-back and flush all changes to the database made from that point up to now on the connection returned by the startThreadConnection() .
 void setAutoCommit(boolean autoCommit)
          Deprecated. You should use the setAutoCommit(DatabaseConnection, boolean) method instead.
 void setAutoCommit(DatabaseConnection connection, boolean autoCommit)
          Set auto-commit mode to be true or false on the connection returned by the startThreadConnection().
 void setObjectCache(boolean enabled)
          Call this with true to enable an object cache for the DAO.
 void setObjectCache(ObjectCache objectCache)
          Same as setObjectCache(boolean) except you specify the actual cache instance to use for the DAO.
 void setObjectFactory(ObjectFactory<T> objectFactory)
          Set an object factory so we can wire in controls over an object when it is constructed.
 DatabaseConnection startThreadConnection()
           WARNING: This method is for advanced users only.
 int update(PreparedUpdate<T> preparedUpdate)
          Update all rows in the table according to the prepared statement argument.
 int update(T data)
          Store the fields from an object to the database.
 UpdateBuilder<T,ID> updateBuilder()
          Like 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 interface com.j256.ormlite.dao.CloseableIterable
closeableIterator
 

Method Detail

queryForId

T queryForId(ID id)
             throws SQLException
Retrieves an object associated with a specific 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

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

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

List<T> queryForAll()
                    throws SQLException
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 iterator() method instead.

Returns:
A list of all of the objects in the table.
Throws:
SQLException - on any SQL problems.

queryForEq

List<T> queryForEq(String fieldName,
                   Object value)
                   throws SQLException
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().

Returns:
A list of the objects in the table that match the fieldName = value;
Throws:
SQLException - on any SQL problems.

queryForMatching

List<T> queryForMatching(T matchObj)
                         throws SQLException
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 queryForMatchingArgs(Object).

Throws:
SQLException

queryForMatchingArgs

List<T> queryForMatchingArgs(T matchObj)
                             throws SQLException
Same as 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.

Throws:
SQLException

queryForFieldValues

List<T> queryForFieldValues(Map<String,Object> fieldValues)
                            throws SQLException
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 queryForFieldValuesArgs(Map).

Throws:
SQLException

queryForFieldValuesArgs

List<T> queryForFieldValuesArgs(Map<String,Object> fieldValues)
                                throws SQLException
Same as 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.

Throws:
SQLException

queryForSameId

T queryForSameId(T data)
                 throws SQLException
Query for a data item in the table that has the same ID as the data parameter.

Throws:
SQLException

queryBuilder

QueryBuilder<T,ID> queryBuilder()
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 query(PreparedQuery) or iterator(PreparedQuery).


updateBuilder

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


deleteBuilder

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


query

List<T> query(PreparedQuery<T> preparedQuery)
              throws SQLException
Query for the items in the object table which match the prepared query. See 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 iterator(PreparedQuery) method instead.

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.

create

int create(T data)
           throws SQLException
Create a new row in the database from an object.

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

T createIfNotExists(T data)
                    throws SQLException
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 queryForId(Object) on it, returning the data if it exists. If it does not exist create(Object) will be called with the parameter.

Returns:
Either the data parameter if it was inserted (now with the ID field set via the create method) or the data element that existed already in the database.
Throws:
SQLException

createOrUpdate

Dao.CreateOrUpdateStatus createOrUpdate(T data)
                                        throws SQLException
This is a convenience method for creating an item in the database if it does not exist. The id is extracted from the data argument and a query-by-id is made on the database. If a row in the database with the same id exists then all of the columns in the database will be updated from the fields in the data parameter. If the id is null (or 0 or some other default value) or doesn't exist in the database then the object will be created in the database. This also means that your data item must have an id field defined.

Returns:
Status object with the number of rows changed and whether an insert or update was performed.
Throws:
SQLException

update

int update(T data)
           throws SQLException
Store 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 updateId(T, ID) .

NOTE: This will not save changes made to foreign objects or to foreign collections.

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.
IllegalArgumentException - If there is only an ID field in the object. See the updateId(T, ID) method.

updateId

int updateId(T data,
             ID newId)
             throws SQLException
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.

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

int update(PreparedUpdate<T> preparedUpdate)
           throws SQLException
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.

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.
IllegalArgumentException - If there is only an ID field in the object. See the updateId(T, ID) method.

refresh

int refresh(T data)
            throws SQLException
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.

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

int delete(T data)
           throws SQLException
Delete an object from the database.

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

int deleteById(ID id)
               throws SQLException
Delete an object from the database that has an 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

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

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

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

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

int delete(PreparedDelete<T> preparedDelete)
           throws SQLException
Delete the objects that match the prepared statement argument.

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

CloseableIterator<T> iterator()
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 closeLastIterator() if you are not iterating across this DAO in multiple threads.

NOTE: With this iterator you can only move forward through the object collection. See the iterator(int) method to create a cursor that can go both directions.

Specified by:
iterator in interface Iterable<T>
Returns:
An iterator of the class that uses SQL to step across the database table.
Throws:
IllegalStateException - When it encounters a SQLException or in other cases.

iterator

CloseableIterator<T> iterator(int resultFlags)
Same as iterator() but while specifying flags for the results. This is necessary with certain database types. The resultFlags could be something like ResultSet.TYPE_SCROLL_INSENSITIVE or other values.

WARNING: Depending on the database type the underlying connection may never be freed -- even if you go all of the way through the results. It is strongly recommended that you call the CloseableIterator.close() method when you are done with the iterator.


iterator

CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery)
                              throws SQLException
Same as iterator() but with a prepared query parameter. See 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();
 }
 

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.

iterator

CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery,
                              int resultFlags)
                              throws SQLException
Same as iterator(PreparedQuery) but while specifying flags for the results. This is necessary with certain database types.

Throws:
SQLException

getWrappedIterable

CloseableWrappedIterable<T> getWrappedIterable()
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();
 }
 


getWrappedIterable

CloseableWrappedIterable<T> getWrappedIterable(PreparedQuery<T> preparedQuery)
Same as getWrappedIterable() but with a prepared query parameter. See queryBuilder() or iterator(PreparedQuery) for more information.


closeLastIterator

void closeLastIterator()
                       throws SQLException
This closes the last iterator returned by the iterator() method.

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

Throws:
SQLException

queryRaw

GenericRawResults<String[]> queryRaw(String query,
                                     String... arguments)
                                     throws SQLException
Similar to the iterator(PreparedQuery) except it returns a GenericRawResults object associated with the SQL select query argument. Although you should use the 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);
 

NOTE: If you are using the StatementBuilder.prepareStatementString() to build your query, it may have added the id column to the selected column list if the Dao object has an id you did not include it in the columns you selected. So the results might have one more column than you are expecting.

Throws:
SQLException

queryRaw

<UO> GenericRawResults<UO> queryRaw(String query,
                                    RawRowMapper<UO> mapper,
                                    String... arguments)
                               throws SQLException
Similar to the 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. For a simple implementation of a raw row mapper, see getRawRowMapper().

Throws:
SQLException

queryRaw

GenericRawResults<Object[]> queryRaw(String query,
                                     DataType[] columnTypes,
                                     String... arguments)
                                     throws SQLException
Similar to the 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.

Throws:
SQLException

queryRawValue

long queryRawValue(String query,
                   String... arguments)
                   throws SQLException
Perform a raw query that returns a single value (usually an aggregate function like MAX or COUNT). If the query does not return a single long value then it will throw a SQLException.

Throws:
SQLException

executeRaw

int executeRaw(String statement,
               String... arguments)
               throws SQLException
Run a raw execute SQL statement to the database. The arguments are optional but can be set with strings to expand ? type of SQL. If you have no arguments, you may want to call executeRawNoArgs(String).

Returns:
number of rows affected.
Throws:
SQLException

executeRawNoArgs

int executeRawNoArgs(String statement)
                     throws SQLException
Run a raw execute SQL statement on the database without any arguments. This may use a different mechanism to execute the query depending on the database backend.

Returns:
number of rows affected.
Throws:
SQLException

updateRaw

int updateRaw(String statement,
              String... arguments)
              throws SQLException
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.

Returns:
number of rows affected.
Throws:
SQLException

callBatchTasks

<CT> CT callBatchTasks(Callable<CT> callable)
                  throws Exception
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. Also, "commit()" is not called on the connection at all. If "auto-commit" is disabled then this will leave it off and nothing will have been persisted.

Throws:
Exception

objectToString

String objectToString(T data)
Return the string version of the object with each of the known field values shown. Useful for testing and debugging.

Parameters:
data - The data item for which we are returning the toString information.

objectsEqual

boolean objectsEqual(T data1,
                     T data2)
                     throws SQLException
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.

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

ID extractId(T data)
             throws SQLException
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.

Throws:
SQLException

getDataClass

Class<T> getDataClass()
Returns the class of the DAO. This is used by internal query operators.


findForeignFieldType

FieldType findForeignFieldType(Class<?> clazz)
Returns the class of the DAO. This is used by internal query operators.


isUpdatable

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


isTableExists

boolean isTableExists()
                      throws SQLException
Returns true if the table already exists otherwise false.

Throws:
SQLException

countOf

long countOf()
             throws SQLException
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.

Throws:
SQLException

countOf

long countOf(PreparedQuery<T> preparedQuery)
             throws SQLException
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.

Throws:
SQLException

assignEmptyForeignCollection

void assignEmptyForeignCollection(T parent,
                                  String fieldName)
                                  throws SQLException
Creates an empty collection and assigns it to the appropriate field in the parent object. 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:
 accoundDao.assignEmptyForeignCollection(account, "orders");
 // this would add it the collection and the internal DAO
 account.orders.add(order1);
 

Parameters:
parent - Parent object that will be associated with all items added to this collection if not already assigned.
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

getEmptyForeignCollection

<FT> ForeignCollection<FT> getEmptyForeignCollection(String fieldName)
                                                throws SQLException
Like assignEmptyForeignCollection(Object, String) but it returns the empty collection that you assign to the appropriate field.

NOTE: May be deprecated in the future.

Throws:
SQLException

setObjectCache

void setObjectCache(boolean enabled)
                    throws SQLException
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 queryRaw(java.lang.String, java.lang.String...) methods.

Throws:
SQLException - If the DAO's class does not have an id field which is required by the ObjectCache.

setObjectCache

void setObjectCache(ObjectCache objectCache)
                    throws SQLException
Same as 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.

Throws:
SQLException - If the DAO's class does not have an id field which is required by the ObjectCache.

getObjectCache

ObjectCache getObjectCache()
Returns the current object-cache being used by the DAO or null if none.


clearObjectCache

void clearObjectCache()
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.


mapSelectStarRow

T mapSelectStarRow(DatabaseResults results)
                   throws SQLException
Return the latest row from the database results from a query to select * (star).

Throws:
SQLException

getSelectStarRowMapper

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

Throws:
SQLException

getRawRowMapper

RawRowMapper<T> getRawRowMapper()
Return a row mapper that is suitable for use with queryRaw(String, RawRowMapper, String...). This is a bit experimental at this time. It most likely will _not_ work with all databases since the string output for each data type is hard to forecast. Please provide feedback.


idExists

boolean idExists(ID id)
                 throws SQLException
Returns true if an object exists that matches this ID otherwise false.

Throws:
SQLException

startThreadConnection

DatabaseConnection startThreadConnection()
                                         throws SQLException

WARNING: This method is for advanced users only. It is only to support the setAutoCommit(DatabaseConnection, boolean) and other methods below. Chances are you should be using the callBatchTasks(Callable) instead of this method unless you know what you are doing.

This allocates a connection for this specific thread that will be used in all other DAO operations. The thread must call endThreadConnection(DatabaseConnection) once it is done with the connection. It is highly recommended that a try { conn = dao.startThreadConnection(); ... } finally { dao.endThreadConnection(conn); } type of pattern be used here to ensure you do not leak connections.

Throws:
SQLException

endThreadConnection

void endThreadConnection(DatabaseConnection connection)
                         throws SQLException

WARNING: This method is for advanced users only. It is only to support the setAutoCommit(DatabaseConnection, boolean) and other methods below. Chances are you should be using the callBatchTasks(Callable) instead of this method unless you know what you are doing.

This method is used to free the connection returned by the startThreadConnection() above.

Parameters:
connection - Connection to be freed. If null then it will be a no-op.
Throws:
SQLException

setAutoCommit

@Deprecated
void setAutoCommit(boolean autoCommit)
                   throws SQLException
Deprecated. You should use the setAutoCommit(DatabaseConnection, boolean) method instead.

Throws:
SQLException

setAutoCommit

void setAutoCommit(DatabaseConnection connection,
                   boolean autoCommit)
                   throws SQLException
Set auto-commit mode to be true or false on the connection returned by the startThreadConnection(). This may not be supported by all database types.

WARNING: Chances are you should be using the callBatchTasks(Callable) instead of this method unless you know what you are doing.

Throws:
SQLException

isAutoCommit

@Deprecated
boolean isAutoCommit()
                     throws SQLException
Deprecated. You should use the isAutoCommit(DatabaseConnection) method instead.

Throws:
SQLException

isAutoCommit

boolean isAutoCommit(DatabaseConnection connection)
                     throws SQLException
Return true if the database connection returned by the startThreadConnection() is in auto-commit mode otherwise false. This may not be supported by all database types.

Throws:
SQLException

commit

void commit(DatabaseConnection connection)
            throws SQLException
If you have previously set auto-commit to false using setAutoCommit(DatabaseConnection, boolean) then this will commit all changes to the database made from that point up to now on the connection returned by the startThreadConnection(). The changes will be written to the database and discarded. The connection will continue to stay in the current auto-commit mode.

WARNING: Chances are you should be using the callBatchTasks(Callable) instead of this method unless you know what you are doing.

Throws:
SQLException

rollBack

void rollBack(DatabaseConnection connection)
              throws SQLException
If you have previously set auto-commit to false using setAutoCommit(DatabaseConnection, boolean) then this will roll-back and flush all changes to the database made from that point up to now on the connection returned by the startThreadConnection() . None of those changes will be written to the database and are discarded. The connection will continue to stay in the current auto-commit mode.

WARNING: Chances are you should be using the callBatchTasks(Callable) instead of this method unless you know what you are doing.

Throws:
SQLException

getConnectionSource

ConnectionSource getConnectionSource()
Return the associated ConnectionSource or null if none set on the DAO yet.


setObjectFactory

void setObjectFactory(ObjectFactory<T> objectFactory)
Set an object factory so we can wire in controls over an object when it is constructed. Set to null to disable the factory.



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