org.nuiton.topia.framework
Class TopiaQuery

java.lang.Object
  extended by org.nuiton.topia.framework.TopiaQuery

public class TopiaQuery
extends Object

Query HQL managment to simplify usage of TopiaContext.find(String, Object...).

TODO-FD20091224 JUnit Tests

 This class is used to construct a HQL query and then execute it from a
 TopiaContext. The TopiaQuery is linked to a TopiaEntity which
 is the main element manipulated in the query. There is two parts in using
 this class :
 - construction of the query, using add, addFrom, addOrder, addSelect,
   addGroup, ...
 - execution of the query, using executeToEntityList, executeToEntity,
   executeToInteger, ...
 

Construction ============

This class make easier the way to construct a HQL query.

Example 1 : -----------

SQL : "SELECT * FROM PersonImpl WHERE firstName LIKE 'M%' AND year > 1980"

HQL using TopiaContext.find(String, Object...) : TopiaContext context = rootContext.beginTransaction(); context.find("FROM " + Person.class.getName() + " WHERE firstName LIKE :firstName AND year > :year", "firstName", "M%", year, 1980);

TopiaQuery : TopiaQuery query = TopiaQuery.createQuery(Person.class).add( Person.FIRST_NAME, Op.LIKE, "M%").add(Person.YEAR, Op.GT, 1980);

But the real advantage is when you have some parameters to test before adding them to the query. With the older method, it was tidious to construct and add parameters to finally use the find method from TopiaContext.

Example 2 : -----------

HQL using TopiaContext.find(String, Object...) : TopiaContext context = rootContext.beginTransaction();

String query = "FROM " + Person.class.getName(); List params = new ArrayList(); String separator = " WHERE "; // company parameter can be null if (company != null) { query += separator + "company = :company"; params.add("company"); params.add(company); separator = " AND "; }

// contact paramater can be null if (contact != null) { query += separator + "contact = :contact"; params.add("contact"); params.add(contact); separator = " AND "; }

context.find(query, params.toArray());

Here we have only two non obligatory params, but imagine if we must have almost 6 or 7 parameters like this !

TopiaQuery : TopiaQuery query = TopiaQuery.createQuery(Person.class);

if (company != null) { query.add(Person.COMPANY, company); }

if (contact != null) { query.add(Person.CONTACT, contact); }

Many ways to create the same query : ------------------------------------

You can use multiple different manners to create a query, it depends on the complexicity. More complex is the query, more easier is to construct it.

HQL : "FROM PersonImpl AS P WHERE (P.company IS NULL OR P.company = :company) AND P.firstName LIKE :firstName"

Using TopiaQuery and an Alias (these different queries are equivalent) : query = TopiaQuery.createQuery(Person.class, "P"); 1- query.add("(P.company IS NULL OR P.company = :company") AND P.firstName LIKE :firstName") .addParam("company", company).addParam("firstName",firstName + "%"); 2- query.add("P.company IS NULL OR P.company = :company") .add("P.firstName LIKE :firstName").addParam("company", company) .addParam("firstName",firstName + "%"); 3- query.add("P.company IS NULL OR P.company = :company") .add("P.firstName", Op.LIKE, firstName + "%") .addParam("company", company); 4- query.addNullOr("P.company", Op.EQ, company). add("P.firstName", Op.LIKE, firstName + "%");

You can use TopiaQuery to create a subquery in an other TopiaQuery, you have to use the method fullQuery() to get the full query in HQL and give it as a string in the other TopiaQuery.

Execution =========

After construction, you can execute the query in different ways.

Default method : ----------------

- execute : as the same result as TopiaContext.find(String, Object...)

Depends on entity type ; ------------------------

- executeToEntity : only one result, the first one - executeToEntityList : all results returned in a List - executeToEntityMap : all results returned in a Map with key defined by user or topiaId by default

For aggregate : ---------------

These methods have in argument the SELECT to execute the query. The previous SELECT (if defined) will not be deleted, but temporarly not used.

- executeToInteger : for example for "SUM", "COUNT" - executeToString : for example for "MAX" - executeCount : directly a "count(*)" - executeToObject : for other type of possible result (Long, Boolean, Double, ...)

Property loading ================

When using Hibernate, some times, Entities linked to the main one will be lazy initialized, but you want them directly when the query will be executed to avoid problems when closing context. You can use the method addLoad(String...) to tell the TopiaQuery to load some properties when executing the query. After that, you don't need to call them for loading them in Hibernate.

The syntax is the same as a property in HQL query using delegation : "person.company" where person and company are entities.

Note : loading only available on collection or entities but not property on a collection of entities which must be made manually.

For a Contact which is linked to a person (entity) and the person linked to company (entity) you can add to a TopiaQuery : query.addLoad("person.company")

For a list of addresses (entity) in the contact you can do : query.addLoad("addresses")

But it's not possible to do for example with meeting (entity) linked to the contact and responsible (entity) linked to a meeting : query.addLoad("meetings.responsible")

Created: 21 déc. 2009

Since:
2.3.0

Mise a jour: $Date: 2011-09-21 09:40:09 +0200 (mer, 21 sep 2011) $ par : $Author: athimel $

Version:
$Revision: 2333 $
Author:
fdesbois

Nested Class Summary
static class TopiaQuery.Op
          Enum to simmplify using operation in query
 
Field Summary
protected  boolean distinct
           
protected  Integer endIndex
           
protected  StringBuilder from
          From part of the query *
static String FROM_SEPARATOR_DEFAULT
           
static String FROM_SEPARATOR_JOIN
           
static String FROM_SEPARATOR_LEFT_JOIN
           
protected  StringBuilder groupBy
          Group By part of the query *
protected  String mainAlias
           
protected  StringBuilder orderBy
          Order By part of the query *
protected  List<Object> params
          Params for HQL query *
protected  boolean parentheses
          Used to determine if parentheses are needed for Where statement *
protected  List<String> propertiesToLoad
           
protected  StringBuilder select
          Select part of the query *
protected  Integer startIndex
           
protected  StringBuilder where
          Where part of the query *
 
Constructor Summary
TopiaQuery()
           
TopiaQuery(Class<? extends TopiaEntity> mainEntityClass)
          Create a TopiaQuery based on the entityClass.
TopiaQuery(Class<? extends TopiaEntity> mainEntityClass, String alias)
          Create a TopiaQuery based on the entityClass.
 
Method Summary
 TopiaQuery add(Map<String,Object> properties)
          Deprecated. since 2.3.4 use addEquals(Map)
 TopiaQuery add(String where)
          Deprecated. since 2.3.4, use addWhere(String) instead
 TopiaQuery add(String paramName, Object... paramValue)
          Deprecated. since 2.3.4, use addEquals(String, Object...) instead
 TopiaQuery add(String paramName, TopiaQuery.Op constraint, Object paramValue)
          Deprecated. since 2.3.4, use addWhere(String, Op, Object) instead
 TopiaQuery addBetween(String paramName, Object value1, Object value2)
          Add an element with BETWEEN operation.
 TopiaQuery addDistinct()
          Add the distinct key word in the query.
 TopiaQuery addEquals(Map<String,Object> properties)
          Add a map of properties to the where clause of the query.
 TopiaQuery addEquals(String paramName, Object... paramValue)
          Add an element to the query.
 TopiaQuery addFetch(String... properties)
          Used to load properties during query execution using FETCH keyword.
 TopiaQuery addFilter(EntityFilter filter)
          Add a filter to the query that contains limit indexes, orderBy condition and referenceId if needed.
 TopiaQuery addFilter(EntityFilter filter, String propertyToFilter)
          Add a filter to the query that contains limit indexes, orderBy condition and referenceId if needed.
 TopiaQuery addFrom(Class<? extends TopiaEntity> entityClass)
          Add an other entity type to the from in the query.
 TopiaQuery addFrom(Class<? extends TopiaEntity> entityClass, String alias)
          Add an other entity type to the from in the query with an alias.
 TopiaQuery addFrom(String str)
          Deprecated. since 2.3.4 use correct addFrom or addJoin or addLeftJoin
protected  TopiaQuery addFrom(String separator, String property, String alias)
          Add an element to the from in the query.
protected  TopiaQuery addFromJoin(String separator, String property, String alias, boolean fetch)
           
 TopiaQuery addGroup(String... group)
          Add an element to the group of the query.
 TopiaQuery addInElements(String elementProperty, String containerProperty)
          Add link constraint between two properties.
 TopiaQuery addJoin(String property, String alias, boolean fetch)
          Add a inner join property to the query with alias.
 TopiaQuery addLeftJoin(String property, String alias, boolean fetch)
          Add a left join property to the query with alias.
 TopiaQuery addLoad(String... properties)
          Add a property to load when query is executed.
 TopiaQuery addNotNull(String paramName)
          Add an element to the query with the constraint Not null.
 TopiaQuery addNull(String paramName)
          Add an element to the query with the constraint null.
 TopiaQuery addNullOr(String paramName, TopiaQuery.Op constraint, Object paramValue)
          Add an element to the query.
 TopiaQuery addOrder(String... order)
          Add an element to the order in the query.
 TopiaQuery addOrderDesc(String order)
           
 TopiaQuery addParam(String id, Object paramValue)
          Add a HQL parameter to the Query.
 TopiaQuery addParams(List<Object> params)
          Add muliple paramaters to the Query.
 TopiaQuery addSelect(String... select)
          Add an element to the select in the query.
 TopiaQuery addSubQuery(String queryPart, TopiaQuery subquery)
          Method used to add a subquery in an existing query.
 TopiaQuery addWhere(String where)
          Add a where element to the Query.
 TopiaQuery addWhere(String paramName, TopiaQuery.Op operator, Object paramValue)
          Add an element to the query.
protected  String convertStringArray(String... array)
          Helper method for array type.
 List execute(TopiaContext transaction)
          Simple execution of the query.
 int executeCount(TopiaContext transaction)
          Execute a simple count on the query, i.e. the number of results get from the query.
<E extends TopiaEntity>
E
executeToEntity(TopiaContext transaction, Class<E> entityClass)
          Execute the query and get the first result entity.
<E extends TopiaEntity>
List<E>
executeToEntityList(TopiaContext transaction, Class<E> entityClass)
          Execute the query and get a List of entity.
<E extends TopiaEntity>
Map<String,E>
executeToEntityMap(TopiaContext transaction, Class<E> entityClass)
          Execute the query and get a Map of entity with topiaId in key.
<E extends TopiaEntity,K>
Map<K,E>
executeToEntityMap(TopiaContext transaction, Class<E> entityClass, String keyName, Class<K> keyClass)
          Execute the query and get a Map of entity with key type in argument.
 int executeToInteger(TopiaContext transaction, String select)
          Execute the query and get an Integer for result.
 Object executeToObject(TopiaContext transaction, String select)
          Execute the query and get an Object for result.
 String executeToString(TopiaContext transaction, String select)
          Execute the query and get a String for result.
protected  void finalize()
           
 String fullQuery()
          Get the full query.
 String getMainAlias()
          Return the mainAlias set from constructor.
 List<Object> getParams()
           
protected  List<String> getPropertiesToLoad()
           
static String getProperty(String... entityProperty)
          This method is used to concat properties from entities.
 String getPropertyCreateDate(String alias)
           
 String getPropertyId(String alias)
           
 String getPropertyVersion(String alias)
           
protected  String getValueName(String paramName)
           
protected
<T extends TopiaEntity>
TopiaEntity
loadEntityProperty(T entity, String property)
          Load a property of type TopiaEntity from an other entity.
protected  void loadProperties(TopiaEntity entity)
          Load all properties for the entity.
protected
<T extends TopiaEntity>
Object
loadProperty(T entity, String property)
          Load a property from an entity.
 TopiaQuery resetLimit()
          Remove limits previously set
 TopiaQuery setFrom(Class<? extends TopiaEntity> mainEntityClass)
          Set the mainEntity in the from part of the query.
 TopiaQuery setFrom(Class<? extends TopiaEntity> mainEntityClass, String alias)
          Set the mainEntity in the from part of the query and use an alias for this mainEntity.
 TopiaQuery setLimit(int start, int end)
          Limit the result of the query with startIndex and endIndex.
 TopiaQuery setMaxResults(int max)
          Set the max results wanted for the query.
 TopiaQuery setSelect(String... select)
          Set the select in the query.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

FROM_SEPARATOR_DEFAULT

public static final String FROM_SEPARATOR_DEFAULT
See Also:
Constant Field Values

FROM_SEPARATOR_JOIN

public static final String FROM_SEPARATOR_JOIN
See Also:
Constant Field Values

FROM_SEPARATOR_LEFT_JOIN

public static final String FROM_SEPARATOR_LEFT_JOIN
See Also:
Constant Field Values

params

protected List<Object> params
Params for HQL query *


select

protected StringBuilder select
Select part of the query *


distinct

protected boolean distinct

from

protected StringBuilder from
From part of the query *


where

protected StringBuilder where
Where part of the query *


orderBy

protected StringBuilder orderBy
Order By part of the query *


groupBy

protected StringBuilder groupBy
Group By part of the query *


startIndex

protected Integer startIndex

endIndex

protected Integer endIndex

parentheses

protected boolean parentheses
Used to determine if parentheses are needed for Where statement *


propertiesToLoad

protected List<String> propertiesToLoad

mainAlias

protected String mainAlias
Constructor Detail

TopiaQuery

public TopiaQuery()

TopiaQuery

public TopiaQuery(Class<? extends TopiaEntity> mainEntityClass)
Create a TopiaQuery based on the entityClass. The from statement is automatically set.

Parameters:
mainEntityClass - used as from part of the query

TopiaQuery

public TopiaQuery(Class<? extends TopiaEntity> mainEntityClass,
                  String alias)
Create a TopiaQuery based on the entityClass. The from statement is automatically set, the select statement must be necessary in some case, the query will manage this case using the mainAlias by default.

Parameters:
mainEntityClass - used as from part of the query
alias - for the mainEntityClass
Method Detail

setFrom

public TopiaQuery setFrom(Class<? extends TopiaEntity> mainEntityClass)
Set the mainEntity in the from part of the query.

Parameters:
mainEntityClass - type of the mainEntity
Returns:
the TopiaQuery

setFrom

public TopiaQuery setFrom(Class<? extends TopiaEntity> mainEntityClass,
                          String alias)
Set the mainEntity in the from part of the query and use an alias for this mainEntity.

Parameters:
mainEntityClass - type of the mainEntity
alias - for the entity in the query
Returns:
the TopiaQuery

addFrom

@Deprecated
public TopiaQuery addFrom(String str)
Deprecated. since 2.3.4 use correct addFrom or addJoin or addLeftJoin

Add an element to the from in the query. Used to add some other data in the query. The default separator used is the ", ".

Parameters:
str - the element to add
Returns:
the TopiaQuery
See Also:
addFrom(Class, String), addJoin(String, String, boolean), addLeftJoin(String, String, boolean)

addFrom

protected TopiaQuery addFrom(String separator,
                             String property,
                             String alias)
Add an element to the from in the query. Used to add some other data in the query or for join as specific separator.

Parameters:
property - the property to add
separator - The separator to use before adding the element (if null the FROM_SEPARATOR_DEFAULT will be used).
Returns:
the TopiaQuery
Since:
2.3.4

addJoin

public TopiaQuery addJoin(String property,
                          String alias,
                          boolean fetch)
Add a inner join property to the query with alias. The join is done in From statement as : FROM Contact C JOIN C.boat B. The added part is 'JOIN C.boat B' using addJoin("C.boat", "B", false). The order of calling addFrom(Class, String) or this method is very important. The first element in the FROM is always the main entity of the query.

Parameters:
property - Property name to use as a Join
alias - Alias of the property in the query
fetch - Add FETCH keyword to load the property in result (avoid lazy initialization)
Returns:
the TopiaQuery
Since:
2.3.4

addLeftJoin

public TopiaQuery addLeftJoin(String property,
                              String alias,
                              boolean fetch)
Add a left join property to the query with alias. The join is done in From statement as : FROM Contact C LEFT JOIN C.boat B. The added part is 'LEFT JOIN C.boat B' using addJoin("C.boat", "B", false). The order of calling addFrom(Class, String) or this method is very important. The first element in the FROM is always the main entity of the query.

Parameters:
property - Property name to use as a Join
alias - Alias of the property in the query
fetch - Add FETCH keyword to load the property in result (avoid lazy initialization)
Returns:
the TopiaQuery
Since:
2.3.4

addFromJoin

protected TopiaQuery addFromJoin(String separator,
                                 String property,
                                 String alias,
                                 boolean fetch)

addFrom

public TopiaQuery addFrom(Class<? extends TopiaEntity> entityClass)
Add an other entity type to the from in the query.

Parameters:
entityClass - different from the mainEntity
Returns:
the TopiaQuery

addFrom

public TopiaQuery addFrom(Class<? extends TopiaEntity> entityClass,
                          String alias)
Add an other entity type to the from in the query with an alias.

Parameters:
entityClass - different from the mainEntity
alias - of the entity in the query
Returns:
the TopiaQuery

fullQuery

public String fullQuery()
Get the full query.

Returns:
a String corresponding to the full query.

addParam

public TopiaQuery addParam(String id,
                           Object paramValue)
Add a HQL parameter to the Query.

Parameters:
id - identification of the param in the query
paramValue - value of the param
Returns:
the TopiaQuery

addParams

public TopiaQuery addParams(List<Object> params)
Add muliple paramaters to the Query. The key of each param will be tested if not already exist in the existing params list and will be renamed in this case.

Parameters:
params - a list of HQL params with key and value in order.
Returns:
the TopiaQuery
See Also:
getValueName(String)

getParams

public List<Object> getParams()

getMainAlias

public String getMainAlias()
Return the mainAlias set from constructor.

Returns:
a String or null if no alias is set

addLoad

public TopiaQuery addLoad(String... properties)
Add a property to load when query is executed. Used to avoid LazyInitializationException for property needed after closing context. The property is a string like those in HQL query.
 Exemples :
 - "person.company" (Property TopiaEntity person linked to the result
   entity in query and company linked to person)
   --> calling myEntity.getPerson().getCompany();
 - "partyRoles" (Property Collection partyRoles linked to the result
   entity in query)
   --> calling myEntity.getPartyRoles().size();
 

Parameters:
properties - List of properties to load
Returns:
the TopiaQuery

addFetch

public TopiaQuery addFetch(String... properties)
Used to load properties during query execution using FETCH keyword. This keyword is used in a JOIN, so the alias is needed to identify properties to load.

Also an empty SELECT statement will be defined to retrieve the correct entity depends on the mainEntity type in the query. Carefull using addFetch, hibernate doesn't support more than 3 or 4 join. In this case, you can use addLoad(String...) or load manually the entities wanted.

Parameters:
properties - Properties to load during query execution
Returns:
the TopiaQuery

getPropertiesToLoad

protected List<String> getPropertiesToLoad()

add

@Deprecated
public TopiaQuery add(String where)
Deprecated. since 2.3.4, use addWhere(String) instead

Parameters:
where - Where statement to add
Returns:
TopiaQuery

addWhere

public TopiaQuery addWhere(String where)
Add a where element to the Query. Could be anything. Parentheses are added automatically (even if there are not needed).

Parameters:
where - element to add
Returns:
the TopiaQuery
Since:
2.3.4

add

@Deprecated
public TopiaQuery add(String paramName,
                                 TopiaQuery.Op constraint,
                                 Object paramValue)
Deprecated. since 2.3.4, use addWhere(String, Op, Object) instead

Parameters:
paramName - name of the parameter to add
constraint - constraint to use
paramValue - value of this parameter
Returns:
TopiaQuery

addWhere

public TopiaQuery addWhere(String paramName,
                           TopiaQuery.Op operator,
                           Object paramValue)
Add an element to the query. The parameter will be automatically added. The operator is needed to determine what type of operation it is. Ex : add("boat", Op.EQ, boat) means -> boat = :boat. Also if the paramValue is Null, the paramName will be added to the query with the constraint null (IS NULL).

TODO-fdesbois-2010-05-26 : maybe manage more than one paramValue with Object... Depends on operator

Parameters:
paramName - the name of the parameter in the query (attribute of the entity)
operator - the operation concerned
paramValue - the value of the parameter (an other entity, a String, ...)
Returns:
the TopiaQuery
Since:
2.3.4

getValueName

protected String getValueName(String paramName)

add

public TopiaQuery add(String paramName,
                      Object... paramValue)
Deprecated. since 2.3.4, use addEquals(String, Object...) instead

Parameters:
paramName - name of the parameter to add
paramValue - value of this parameter
Returns:
TopiaQuery
Since:
2.3.1

addEquals

public TopiaQuery addEquals(String paramName,
                            Object... paramValue)
Add an element to the query. The parameter will be automatically added. The default constrainst operation is Op.EQ for EQUALS. Ex : add("boat", boat) means -> boat = :boat. If you add more than one values, the statement IN will be used. You can also have a null value in the paramValue list (except if it's the only one value, it's ambiguous). Note : this method do nothing if the paramValue is not defined. You can also set paramValue to null if you want the paramName to be null in the query.

Parameters:
paramName - name of the parameter in the query
paramValue - values of the parameter
Returns:
the TopiaQuery
Since:
2.3.4
See Also:
addWhere(String, Op, Object)

add

@Deprecated
public TopiaQuery add(Map<String,Object> properties)
Deprecated. since 2.3.4 use addEquals(Map)

Parameters:
properties - map of the properties to add
Returns:
TopiaQuery

addEquals

public TopiaQuery addEquals(Map<String,Object> properties)
Add a map of properties to the where clause of the query. Each property will be added to the query with Op.EQ operation, the key in the map is the property name, and the value is the value of the parameter in the query.

Parameters:
properties - to add to the query
Returns:
the TopiaQuery
Since:
2.3.4

addNotNull

public TopiaQuery addNotNull(String paramName)
Add an element to the query with the constraint Not null.

Parameters:
paramName - name of the parameter in the query
Returns:
the TopiaQuery

addNullOr

public TopiaQuery addNullOr(String paramName,
                            TopiaQuery.Op constraint,
                            Object paramValue)
Add an element to the query. The nullity is tested or a constraint is added for that element. Ex : addNullOr("begin", Op.GT, new Date()) means begin IS NULL OR begin > :begin (where :begin = new Date()).

Parameters:
paramName - the name of the parameter in the query (attribute of the entity)
constraint - the operation concerned by the or
paramValue - the value of the parameter (an other entity, a String, ...)
Returns:
the TopiaQuery

addNull

public TopiaQuery addNull(String paramName)
Add an element to the query with the constraint null.

Parameters:
paramName - name of the parameter in the query
Returns:
the TopiaQuery

addBetween

public TopiaQuery addBetween(String paramName,
                             Object value1,
                             Object value2)
Add an element with BETWEEN operation. The paramName will be found between value1 and value2. Useful for date manipulations.

Parameters:
paramName - The name of the parameter in the query (entity property)
value1 - First value
value2 - Second value
Returns:
the TopiaQuery

addInElements

public TopiaQuery addInElements(String elementProperty,
                                String containerProperty)
Add link constraint between two properties. elementProperty is in elements of containerProperty which is a collection with same type than elementProperty. (HQL : elementProperty IN elements (containerProperty))

Parameters:
elementProperty - contains in containerProperty collection
containerProperty - collection which contains elementProperty
Returns:
the TopiaQuery
Since:
2.3.4

addSubQuery

public TopiaQuery addSubQuery(String queryPart,
                              TopiaQuery subquery)
Method used to add a subquery in an existing query. The params will be automatically checked and copied from the subquery to the current one. This method is used to inject subquery in WHERE part of the query. The queryPart is the element in the query to bind with the subquery. The ? character is used to inject the subquery into the queryPart. Ex :
 // Add a SUB_ELMT = (subquery) into the query
 query.addSubQuery("SUB_ELMT = (?)", subquery, false);
 

Parameters:
queryPart - part of the query where subquery need to be injected
subquery - existing topiaQuery as subquery
Returns:
the TopiaQuery
Since:
2.3.4
See Also:
getValueName(String)

addSelect

public TopiaQuery addSelect(String... select)
Add an element to the select in the query. Depends on the result wanted in execute methods. The main entity will be automatically added only if an alias is initialize from constructor. If you want only this select element, use setSelect(String...) method instead.

Parameters:
select - element to add
Returns:
the TopiaQuery

setSelect

public TopiaQuery setSelect(String... select)
Set the select in the query. Depends on the result wanted in execute methods.

Parameters:
select - element to set
Returns:
the TopiaQuery

addDistinct

public TopiaQuery addDistinct()
Add the distinct key word in the query. The result will not have multiple same values.

Returns:
the TopiaQuery

addOrder

public TopiaQuery addOrder(String... order)
Add an element to the order in the query. Used to add some parameters to order by.

Parameters:
order - element to add
Returns:
the TopiaQuery

addOrderDesc

public TopiaQuery addOrderDesc(String order)

addGroup

public TopiaQuery addGroup(String... group)
Add an element to the group of the query. Used to add some paramters to group by.

Parameters:
group - element to add
Returns:
the TopiaQuery

convertStringArray

protected String convertStringArray(String... array)
Helper method for array type. Each value will be separated by a comma. TODO-fdesbois-2010-05-25 : replace this algo by StringUtil.join()

Parameters:
array - of String
Returns:
a String with values of the array separated by a comma

setLimit

public TopiaQuery setLimit(int start,
                           int end)
Limit the result of the query with startIndex and endIndex.

Parameters:
start - first index to get from the results
end - last index to get from the results
Returns:
the TopiaQuery

resetLimit

public TopiaQuery resetLimit()
Remove limits previously set

Returns:
the TopiaQuery

setMaxResults

public TopiaQuery setMaxResults(int max)
Set the max results wanted for the query.

Parameters:
max - the number of elements wanted
Returns:
the TopiaQuery

addFilter

public TopiaQuery addFilter(EntityFilter filter)
                     throws IllegalArgumentException
Add a filter to the query that contains limit indexes, orderBy condition and referenceId if needed. The referenceProperty is necessary to use the referenceId of the filter. The filter will be applied on the main entity in the query (using the mainAlias if necessary).

Note : the default orderBy is the topiaCreateDate ordered desc (the most recent in first)

Parameters:
filter - Filter to apply on the query
Returns:
the TopiaQuery
Throws:
IllegalArgumentException - if referenceId is defined but no referenceProperty was set
See Also:
addFilter(EntityFilter, String)

addFilter

public TopiaQuery addFilter(EntityFilter filter,
                            String propertyToFilter)
                     throws IllegalArgumentException
Add a filter to the query that contains limit indexes, orderBy condition and referenceId if needed. In some case it's necessary to specify explicitely the propertyToFilter in complex queries. The referenceProperty need to be specifie in filter to have a correspondance between the referenceId and it's property in the query. By default, the propertyToFilter is the mainAlias of the query.

Note : the default orderBy is the topiaCreateDate ordered desc (the most recent in first)

Parameters:
filter - Filter to apply on the query
propertyToFilter - Explicit property to filter
Returns:
the TopiaQuery
Throws:
IllegalArgumentException - if referenceId is defined but no referenceProperty was set

execute

public List execute(TopiaContext transaction)
             throws TopiaException
Simple execution of the query. This method use directly the find method in TopiaContext interface.

Parameters:
transaction - the TopiaContext to use for execution
Returns:
a List of results
Throws:
TopiaException - for error on query execution
See Also:
TopiaContext.find(String, Object...)

executeToEntityList

public <E extends TopiaEntity> List<E> executeToEntityList(TopiaContext transaction,
                                                           Class<E> entityClass)
                                                throws TopiaException,
                                                       ClassCastException
Execute the query and get a List of entity. Some properties will be loaded if they are prealably set using $addLoad(String...).

Type Parameters:
E - entity type
Parameters:
transaction - the TopiaContext to use for execution
entityClass - used to check return type of execution results
Returns:
a List of TopiaEntity corresponding to the entityClass in argument
Throws:
TopiaException - for error on query execution
ClassCastException - if entityClass doesn't match to results

executeToEntityMap

public <E extends TopiaEntity,K> Map<K,E> executeToEntityMap(TopiaContext transaction,
                                                             Class<E> entityClass,
                                                             String keyName,
                                                             Class<K> keyClass)
                                                throws TopiaException,
                                                       ClassCastException
Execute the query and get a Map of entity with key type in argument. Some properties will be loaded if they are prealably set using $addLoad(String...).

Type Parameters:
E - entity type
K - the type of the map key
Parameters:
transaction - the TopiaContext to use for execution
entityClass - needed to execute the query
keyName - the property name of the key in the entity
keyClass - the key class for the result map
Returns:
a Map with the key type defined and the entity in value
Throws:
TopiaException - for error on query execution
ClassCastException - if entityClass doesn't match to results

executeToEntityMap

public <E extends TopiaEntity> Map<String,E> executeToEntityMap(TopiaContext transaction,
                                                                Class<E> entityClass)
                                                     throws TopiaException,
                                                            ClassCastException
Execute the query and get a Map of entity with topiaId in key. Some properties will be loaded if they are prealably set using $addLoad(String...).

Type Parameters:
E - entity type
Parameters:
transaction - the TopiaContext to use for execution
entityClass - used to check return type of execution results
Returns:
a Map with the key type defined and the entity in value
Throws:
TopiaException - for error on query execution
ClassCastException - if entityClass doesn't match to results

executeToEntity

public <E extends TopiaEntity> E executeToEntity(TopiaContext transaction,
                                                 Class<E> entityClass)
                                      throws TopiaException,
                                             ClassCastException
Execute the query and get the first result entity. Some properties will be loaded if they are prealably set using $addLoad(String...).

Type Parameters:
E - entity type
Parameters:
transaction - the TopiaContext to use for execution
entityClass - used to check return type of execution results
Returns:
a TopiaEntity corresponding to the entityClass in argument
Throws:
TopiaException - for error on query execution
ClassCastException - if entityClass doesn't match to results

executeToObject

public Object executeToObject(TopiaContext transaction,
                              String select)
                       throws TopiaException
Execute the query and get an Object for result. The select is overriden to get only the right value for return.

Parameters:
transaction - the TopiaContext to use for execution
select - the Select overriden
Returns:
an Object
Throws:
TopiaException - for error on query execution

executeToInteger

public int executeToInteger(TopiaContext transaction,
                            String select)
                     throws TopiaException
Execute the query and get an Integer for result. Used only for query with aggration select which return a Long : COUNT, SUM ... The select is overriden to get only the right value for return.

Parameters:
transaction - the TopiaContext to use for execution
select - the Select overriden (ex : SUM(myParam))
Returns:
an Integer
Throws:
TopiaException - for error on query execution

executeToString

public String executeToString(TopiaContext transaction,
                              String select)
                       throws TopiaException
Execute the query and get a String for result. Used for query with MAX, ... The select is overriden to get only the right value for return.

Parameters:
transaction - the TopiaContext to use for execution
select - the Select overriden (ex : MAX(myParam))
Returns:
a String
Throws:
TopiaException - for error on query execution

executeCount

public int executeCount(TopiaContext transaction)
                 throws TopiaException
Execute a simple count on the query, i.e. the number of results get from the query. The order is not considered to count the elements and will be temporarly disabled. The distinct constraint will be manage if necessary :
 COUNT(DISTINCT mainAlias)
 

Parameters:
transaction - the TopiaContext to use for execution
Returns:
an int corresponding to the number of result in the query
Throws:
TopiaException - for error on query execution

loadProperties

protected void loadProperties(TopiaEntity entity)
                       throws TopiaException
Load all properties for the entity.

Parameters:
entity - used to load properties
Throws:
TopiaException - for error on query execution

loadEntityProperty

protected <T extends TopiaEntity> TopiaEntity loadEntityProperty(T entity,
                                                                 String property)
                                  throws TopiaException
Load a property of type TopiaEntity from an other entity.

Type Parameters:
T - type of the entity extends TopiaEntity
Parameters:
entity - used to load the property
property - name of the property in the entity
Returns:
a TopiaEntity corresponding to the property loaded
Throws:
TopiaException - for error on query execution

loadProperty

protected <T extends TopiaEntity> Object loadProperty(T entity,
                                                      String property)
                       throws TopiaException
Load a property from an entity.

Type Parameters:
T - type of the entity extends TopiaEntity
Parameters:
entity - used to load the property
property - name of the property in the entity
Returns:
an Object corresponding to the property loaded
Throws:
TopiaException - for error loading property (encapsulate IllegalACessException, InvocationTargetException, NoSuchMethodException)

getProperty

public static String getProperty(String... entityProperty)
This method is used to concat properties from entities. Ex in HQL you can have boat.shipOwner.name, these properties are defined as constants in each entity associated (SHIP_OWNER in Boat entity, NAME in ShipOwner entity) so you just have to call this method as :
 getProperty("boat", Boat.SHIP_OWNER, ShipOwner.NAME);
 // will return boat.shipOwner.name
 

It's better to use constants instead of directly the string chain to avoid problems on changing property name in model. Furthermore it's better to use this method instead of doing :

 "boat." + Boat.SHIP_OWNER + "." + ShipOwner.NAME
 

Parameters:
entityProperty - to concat
Returns:
the string chain with properties separated with a dot

getPropertyId

public String getPropertyId(String alias)

getPropertyCreateDate

public String getPropertyCreateDate(String alias)

getPropertyVersion

public String getPropertyVersion(String alias)

finalize

protected void finalize()
                 throws Throwable
Overrides:
finalize in class Object
Throws:
Throwable

toString

public String toString()
Overrides:
toString in class Object


Copyright © 2004-2011 CodeLutin. All Rights Reserved.