com.objectwave.persist
Class SQLQuery

java.lang.Object
  |
  +--com.objectwave.transactionalSupport.ObjectEditor
        |
        +--com.objectwave.persist.SQLQuery
All Implemented Interfaces:
ObjectEditingView, java.io.Serializable, SetAndGetDelegateIF

public class SQLQuery
extends ObjectEditor
implements java.io.Serializable

Used to define dynamic queries at an object level. This is intended to allow a developer to never include SQL code in their development efforts. For example:

SQLQuery query = new SQLQuery(somePersistentObject);
somePersistentObject.setAttributeValue("one");
query.find();
This should return a vector containing instances of SomePersistentObject. The query would be constrained by those cases that AttributeValue = "one";

Version:
$Id: SQLQuery.java,v 2.7 2002/08/24 13:08:07 dave_hoag Exp $
Author:
Dave Hoag
See Also:
Persistence, Broker, Serialized Form

Nested Class Summary
static class SQLQuery.Test
          Unit test
 
Nested classes inherited from class com.objectwave.transactionalSupport.ObjectEditor
ObjectEditor.Test
 
Field Summary
protected  boolean attributeSearch
           
protected  Broker brok
           
protected  CollectionAdapter collectionAdapter
           
protected  Persistence constraint
           
protected  java.util.HashMap constraints
           
protected static Broker defaultBroker
           
protected  boolean distinct
           
protected  int objectLimit
           
protected  java.util.Vector orderByList
           
protected  boolean queryLike
           
protected  Persistence subject
           
protected  java.util.Vector subQuery
           
 
Fields inherited from class com.objectwave.transactionalSupport.ObjectEditor
dataExchange, fds, security
 
Constructor Summary
SQLQuery()
          When using this constructor, before this query would be valid you MUST call the setSubject method.
SQLQuery(Persistence obj)
          Create a query object that will be used to locate persistent objects.
 
Method Summary
 void addConstraint(Constraint constraint)
          Add a constraint to the query.
 void addOrderByField(java.lang.String pathToField)
          Add a new element to our list of order by clauses.
 void addOrderByField(java.lang.String pathToField, boolean descend)
          Add a new element to our list of order by clauses.
 int count()
          Return a collection of persistent objects of the type of this current query's subject.
 void deleteAll()
          Delete all records that match the search criteria.
 boolean fieldIsConstrained(java.lang.String field)
          Determine if there is a constraint assigned for the provided field name.
 java.util.Vector find()
          Return a collection of persistent objects of the type of this current query's subject.
 java.util.Vector findAttributes(java.lang.String[] attributes)
          Return a vector of Object [].
 java.lang.Object findCollection()
          Return a collection of persistent objects of the type of this current query's subject.
 java.lang.Object findCollection(java.lang.Class clazz)
          Return a collection of persistent objects of the type of this current query's subject.
 java.util.Vector findIn(Persistence obj)
           
 Persistence findUnique()
          Find the one and only one persistent object that matches our Query conditions.
 Broker getBroker()
          If the broker is explicitly set, use that broker.
 java.util.List getChildConstraintFor(java.lang.String field)
          How do we deal with multiple constraints on a given field? Answer: we don't.
 CollectionAdapter getCollectionAdapter()
          Used when building result sets.
 Constraint getConstraintFor(java.lang.String field)
          How do we deal with multiple constraints on a given field? Answer: we don't.
static Broker getDefaultBroker()
          A SQLQuery object can be pegged to a specific broker.
 Persistence getJoinConstraint()
          Gets the JoinConstraint attribute of the SQLQuery object
 int getObjectLimit()
           
 java.util.Vector getOrderByList()
          Each string in the vector is a path to the field we wish to use.
 Persistence getSubject()
          The main subject of this query.
 boolean isAttributeSearch()
          Gets the AttributeSearch attribute of the SQLQuery object
 boolean isDistinct()
          Gets the Distinct attribute of the SQLQuery object
 boolean isLike()
          Should we default the comparison of values (when using query by example) to be a 'LIKE' comparison.
protected  int populateStack(java.util.Vector symbols, int idx, java.util.Stack currentStack)
          Examine the symbols and build constraints from the information.
protected  int processBracket(StringCalculator.CalcItem calcItem, java.util.Vector symbols, int idx, java.util.Stack currentStack)
          The setConstraintString has detected and opening '('.
protected  void processOperator(StringCalculator.CalcItem calcItem, java.util.Vector symbols, int idx, java.util.Stack currentStack)
          The constraint string has found an operation (like '=' or '&&') and it needs to build the appropriate Constraint object.
static void registerCollectionAdapter(java.lang.Class collectionClass, java.lang.Class adapter)
          To support different collection types, multiple collection adapters must be registered.
 void set(java.lang.reflect.Field adapt, java.lang.Object val, java.lang.Object originalVal)
          If we set any field on this object that also happens to be a persistent object, wrap it with a SQLQuery.
 void setAsLike(boolean value)
          Should we default the comparison of values (when using query by example) to be a 'LIKE' comparison.
 void setBroker(Broker b)
          Set broker for which this query is to use.
 void setCollectionAdapter(CollectionAdapter adapter)
          This method may be to powerfull for its own good.
 void setConstraint(Persistence p)
           
 void setConstraintString(java.lang.String constraints)
          Attempt to simplify the creation of constraints.
static void setDefaultBroker(Broker b)
          When a query is executed, it needs to be executed against a specific broker.
 void setDistinct(boolean b)
          Should only distinct rows be found.
 void setFieldConstraint(Persistence search, java.lang.String fieldPath, java.lang.String value, java.lang.String compareConstraintType)
          Convenience method for setting field constraints.
 void setIsanyOf(Persistence p, java.lang.String fieldName, java.util.Vector anyOf)
          Determine that all elements of the result set must have a value in the given field (indicated by fieldName) which occurs as an element "anyOf".
 void setIsNotNull(Persistence p, java.lang.String fieldName)
          We can provide our own objects for the comparison.
 void setIsNull(Persistence p, java.lang.String fieldName)
          We can provide our own objects for the comparison.
 void setNotAnyOf(Persistence p, java.lang.String fieldName, java.util.Vector anyOf)
          Similar to setIsAnyOf, but the "inverse" of the results
 void setObjectLimit(int num)
          Limit the number of objects that can be created through this query.
 void setOrderByList(java.util.Vector v)
          Field paths that are used to order the result set.
 void setSubject(Persistence obj)
          The basis of a JGringer query is the concept of Query by Example.
 void setSubSelect(Persistence p, java.lang.String fieldPath, java.lang.String subSelectFieldPath, SQLQuery subSelectQuery, boolean isNot)
           
protected  java.lang.String stripTicks(java.lang.String aValue)
          The constraint string uses \' (ticks) to denote string boundaries.
 java.lang.String toString()
          Try to provide some useful debugging information.
 
Methods inherited from class com.objectwave.transactionalSupport.ObjectEditor
changes, clearChanges, clearChanges, commit, containsAnyChanges, containsAttributeChanges, get, get, get, get, get, get, get, get, get, get, getCollectionChanges, getDomainField, getDomainObject, getFieldMap, getMods, getSecurity, getValue, isDirty, isTransient, lock, lockedBy, markChange, migrateChanges, noKnownLogs, putFieldMap, putMod, quickChanges, rollback, set, set, set, set, set, set, set, set, set, set, setAsTransient, setDomainField, setSecurity, setValue, unlock
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

defaultBroker

protected static Broker defaultBroker

constraints

protected java.util.HashMap constraints

brok

protected transient Broker brok

subject

protected Persistence subject

queryLike

protected boolean queryLike

distinct

protected boolean distinct

attributeSearch

protected boolean attributeSearch

subQuery

protected java.util.Vector subQuery

collectionAdapter

protected CollectionAdapter collectionAdapter

orderByList

protected java.util.Vector orderByList

constraint

protected Persistence constraint

objectLimit

protected int objectLimit
Constructor Detail

SQLQuery

public SQLQuery()
When using this constructor, before this query would be valid you MUST call the setSubject method.

See Also:
setSubject(com.objectwave.persist.Persistence)

SQLQuery

public SQLQuery(Persistence obj)
Create a query object that will be used to locate persistent objects.

Parameters:
obj - An object implmenting Persistence interface.
Method Detail

setDefaultBroker

public static void setDefaultBroker(Broker b)
When a query is executed, it needs to be executed against a specific broker. It is possible for the persistent subject to specify the broker but it many cases the subject will not identify a specific broker. In those cases, the default broker (set here) will be broker processing the query.

Parameters:
b - The new DefaultBroker value

getDefaultBroker

public static Broker getDefaultBroker()
A SQLQuery object can be pegged to a specific broker. That broker is known as the default broker.

Returns:
An implementation of the Broker interface.

registerCollectionAdapter

public static void registerCollectionAdapter(java.lang.Class collectionClass,
                                             java.lang.Class adapter)
                                      throws java.lang.IllegalArgumentException
To support different collection types, multiple collection adapters must be registered.

Parameters:
adapter - It is assumed that this class implements the CollectionAdapter interface.
collectionClass - The 'type' that is built by this collection adapter.
Throws:
java.lang.IllegalArgumentException - If the adapter parameter does not implement the CollectionAdapter interface.

setSubject

public void setSubject(Persistence obj)
The basis of a JGringer query is the concept of Query by Example. In other words, "I want all objects that look like this one". Since this is our fundamental query capability, we always need a 'subject' of a query. This method allows the subject to be set and become our 'example' for the query.

Parameters:
obj - The example object we are using as the basis of the query

setObjectLimit

public void setObjectLimit(int num)
Limit the number of objects that can be created through this query.

Parameters:
num - The limit on the number of objects to create.

set

public void set(java.lang.reflect.Field adapt,
                java.lang.Object val,
                java.lang.Object originalVal)
If we set any field on this object that also happens to be a persistent object, wrap it with a SQLQuery.

Specified by:
set in interface SetAndGetDelegateIF
Overrides:
set in class ObjectEditor
Parameters:
adapt -
val -
originalVal -
See Also:
#setValue(java.lang.Field, java.lang.Object, java.lang.Object)

setAsLike

public void setAsLike(boolean value)
Should we default the comparison of values (when using query by example) to be a 'LIKE' comparison.

Parameters:
value - boolean indicating if this should be a "like" query

setBroker

public void setBroker(Broker b)
Set broker for which this query is to use.

Parameters:
b - The new Broker value

setCollectionAdapter

public void setCollectionAdapter(CollectionAdapter adapter)
This method may be to powerfull for its own good. It allows the developer to force the result set to be a certain type.

Parameters:
adapter - The new CollectionAdapter value

setConstraint

public void setConstraint(Persistence p)
Parameters:
p - The new Constraint value

setConstraintString

public void setConstraintString(java.lang.String constraints)
                         throws java.text.ParseException
Attempt to simplify the creation of constraints. Building constraints is a multiple step process, this is an attempt to simplify the creation of simple constraints. Complex constraints are not yet supported.

Parameters:
constraints - A simple string like "name = 'Dave' && orderSize < 10"
Throws:
java.text.ParseException - The provided string is not valid

setDistinct

public void setDistinct(boolean b)
Should only distinct rows be found.

Parameters:
b - The new Distinct value

setFieldConstraint

public void setFieldConstraint(Persistence search,
                               java.lang.String fieldPath,
                               java.lang.String value,
                               java.lang.String compareConstraintType)
Convenience method for setting field constraints.

Parameters:
search - The persistent object that has the field?
fieldPath - Field of the 'search' param?
value - The value to use in the comparison.
compareConstraintType - A simple comparison type '=', ' <=', etc....

setSubSelect

public void setSubSelect(Persistence p,
                         java.lang.String fieldPath,
                         java.lang.String subSelectFieldPath,
                         SQLQuery subSelectQuery,
                         boolean isNot)
Parameters:
p - The new SubSelect value
fieldPath - The new SubSelect value
subSelectFieldPath - The new SubSelect value
subSelectQuery - The new SubSelect value
isNot - The new SubSelect value

setIsanyOf

public void setIsanyOf(Persistence p,
                       java.lang.String fieldName,
                       java.util.Vector anyOf)
Determine that all elements of the result set must have a value in the given field (indicated by fieldName) which occurs as an element "anyOf".

Parameters:
p - The new IsanyOf value
fieldName - The new IsanyOf value
anyOf - The new IsanyOf value

setIsNotNull

public void setIsNotNull(Persistence p,
                         java.lang.String fieldName)
We can provide our own objects for the comparison. If the parameter p is null, we will default it to be the subject of this query. Find all of the objects where the field specified is not null.

Parameters:
p - The new IsNotNull value
fieldName - The new IsNotNull value

setIsNull

public void setIsNull(Persistence p,
                      java.lang.String fieldName)
We can provide our own objects for the comparison. If the parameter p is null, we will default it to be the subject of this query. Find all of the objects where the field specified is null.

Parameters:
p - The new IsNull value
fieldName - The new IsNull value

setNotAnyOf

public void setNotAnyOf(Persistence p,
                        java.lang.String fieldName,
                        java.util.Vector anyOf)
Similar to setIsAnyOf, but the "inverse" of the results

Parameters:
p - The new NotAnyOf value
fieldName - The new NotAnyOf value
anyOf - The new NotAnyOf value

setOrderByList

public void setOrderByList(java.util.Vector v)
Field paths that are used to order the result set.

Parameters:
v - Vector of Strings.
See Also:
getOrderByList()

getJoinConstraint

public Persistence getJoinConstraint()
Gets the JoinConstraint attribute of the SQLQuery object

Returns:
The JoinConstraint value

isAttributeSearch

public boolean isAttributeSearch()
Gets the AttributeSearch attribute of the SQLQuery object

Returns:
The AttributeSearch value

isDistinct

public boolean isDistinct()
Gets the Distinct attribute of the SQLQuery object

Returns:
The Distinct value

getObjectLimit

public int getObjectLimit()
Returns:
int The number of objects this query will legally be allowed to return.

getBroker

public Broker getBroker()
If the broker is explicitly set, use that broker. Next check the query object's BrokerName. Finally, try using the default broker associated for all SQLQueries. This must ALWAYS return some broker or the query will fail with a null pointer exception.

Returns:
An implementation of the Broker interface.

getCollectionAdapter

public CollectionAdapter getCollectionAdapter()
Used when building result sets. This will usually be null.

Returns:
The collection adapter that will build the result set values.

getConstraintFor

public Constraint getConstraintFor(java.lang.String field)
How do we deal with multiple constraints on a given field? Answer: we don't.

Parameters:
field - The name of a constrained field.
Returns:
Constraint for the given field.

getChildConstraintFor

public java.util.List getChildConstraintFor(java.lang.String field)
How do we deal with multiple constraints on a given field? Answer: we don't.

Parameters:
field - The name of a constrained field.
Returns:
Constraint for the given field.

getSubject

public Persistence getSubject()
The main subject of this query. This query will always return a vector of the subject objects (or subclasses...).

Returns:
The Subject value

isLike

public boolean isLike()
Should we default the comparison of values (when using query by example) to be a 'LIKE' comparison.

Returns:
The Like value

getOrderByList

public java.util.Vector getOrderByList()
Each string in the vector is a path to the field we wish to use. Each path begins with from the subject of this query. ex. Assume the subect is an instance of an Order class. Assume the order class contains an amount and a reference to a class called OrderId. Assume OrderId has a field called id. Assume a query is created that is looking for a Orders and their respective OrderId. Valid paths include: amount orderId.id orderId <==This one uses the foreign key as the order by element The order that the elements appear in the list is the order they will appear in the order by clause.

Returns:
The OrderByList value

addConstraint

public void addConstraint(Constraint constraint)
Add a constraint to the query. A constraint is some restriction on the field values. Typical usage may constrain where a value is < another value.

Parameters:
constraint - The constraint object representing the restricted values.

count

public int count()
          throws QueryException
Return a collection of persistent objects of the type of this current query's subject.

Returns:
A Vector of persistent objects.
Throws:
QueryException

fieldIsConstrained

public boolean fieldIsConstrained(java.lang.String field)
Determine if there is a constraint assigned for the provided field name.

Parameters:
field -
Returns:
boolean true if a field constraint is defined.
See Also:
addConstraint(Constraint)

find

public java.util.Vector find()
                      throws QueryException
Return a collection of persistent objects of the type of this current query's subject. The return type of Object allows any collection type. NOTE: This may have a side effect of modifying the state of this object. The collectionAdapter field will be set to null.

Returns:
A Vector of persistent objects.
Throws:
QueryException

findCollection

public java.lang.Object findCollection()
                                throws QueryException
Return a collection of persistent objects of the type of this current query's subject. The return type of Object allows any collection type. NOTE: This may have a side effect of modifying the state of this object. The collectionAdapter field may be set to null.

Returns:
A Collection of persistent objects.
Throws:
QueryException

findAttributes

public java.util.Vector findAttributes(java.lang.String[] attributes)
                                throws QueryException
Return a vector of Object []. Each Object [] will contain the values for the attribute list.

Parameters:
attributes - A list of the attributes that are to be retrieved.
Returns:
A Vector of Object [].
Throws:
QueryException

findCollection

public java.lang.Object findCollection(java.lang.Class clazz)
                                throws QueryException
Return a collection of persistent objects of the type of this current query's subject. The return type of Object allows any collection type.

Parameters:
clazz - The class of object we want as the result set value
Returns:
A Vector of persistent objects.
Throws:
QueryException

findIn

public java.util.Vector findIn(Persistence obj)
                        throws QueryException
Parameters:
obj - is an object that can join with the subject of this query.
Returns:
Throws:
QueryException

findUnique

public Persistence findUnique()
                       throws QueryException
Find the one and only one persistent object that matches our Query conditions. NULL is a valid return type.

Returns:
The object that matches the search criteria.
Throws:
QueryException - One of the following occured:
  • More than one object is found
  • A database specific exception occurred

  • addOrderByField

    public void addOrderByField(java.lang.String pathToField)
    Add a new element to our list of order by clauses.

    Parameters:
    pathToField - The feature to be added to the OrderByField attribute
    See Also:
    getOrderByList()

    addOrderByField

    public void addOrderByField(java.lang.String pathToField,
                                boolean descend)
    Add a new element to our list of order by clauses.

    Parameters:
    descend - If true, sort the results in descending order.
    pathToField - The feature to be added to the OrderByField attribute
    See Also:
    getOrderByList()

    deleteAll

    public void deleteAll()
                   throws QueryException
    Delete all records that match the search criteria. This is a very powerfull method, use sparingly.

    Throws:
    QueryException

    populateStack

    protected int populateStack(java.util.Vector symbols,
                                int idx,
                                java.util.Stack currentStack)
                         throws java.text.ParseException
    Examine the symbols and build constraints from the information. The supplied stack will contain one and only one constraint object when this method returns. This method can be used as a part of a recursive algorithm to handle parens "( )". This method will terminate when a closing paren ")" is encountered, therefore all values in the list of symbols may not be processed.

    Parameters:
    symbols - The reverse polish notation of all the symbols in the constraint string.
    idx - The current index of the element to process within the symbols vector
    currentStack - The holder of the created Constraint objects.
    Returns:
    The last processed symbol within the vector of symbols
    Throws:
    java.text.ParseException - Something wasn't right about the constraint string

    processOperator

    protected void processOperator(StringCalculator.CalcItem calcItem,
                                   java.util.Vector symbols,
                                   int idx,
                                   java.util.Stack currentStack)
                            throws java.text.ParseException
    The constraint string has found an operation (like '=' or '&&') and it needs to build the appropriate Constraint object.

    Parameters:
    calcItem - An item found within the constratint string
    symbols - The reverse polish notation of all the symbols in the constraint string.
    idx - The current index of the current operation within the symbols
    currentStack - The holder of the created Constraint objects.
    Throws:
    java.text.ParseException - The boolean expression did not use the correct symbols

    stripTicks

    protected java.lang.String stripTicks(java.lang.String aValue)
    The constraint string uses \' (ticks) to denote string boundaries. Since these ticks should not be considered a part of the value, we attempt to strip them here.

    Parameters:
    aValue - Like "'aValue'"
    Returns:
    Ticks removed like "aValue"

    processBracket

    protected int processBracket(StringCalculator.CalcItem calcItem,
                                 java.util.Vector symbols,
                                 int idx,
                                 java.util.Stack currentStack)
                          throws java.text.ParseException
    The setConstraintString has detected and opening '('. This method uses recursion to process the contents of the "( )" brackets as a single standalone element.

    Parameters:
    calcItem - An item found within the constratint string
    symbols - The reverse polish notation of all the symbols in the constraint string.
    idx - The current index of the "(" within the symbols vector
    currentStack - The holder of the created Constraint objects.
    Returns:
    The last processed symbol within the vector of symbols
    Throws:
    java.text.ParseException - Something wasn't right within the brackets.

    toString

    public java.lang.String toString()
    Try to provide some useful debugging information.

    Overrides:
    toString in class java.lang.Object