Class SQLTemplate<T>
- Type Parameters:
T- the type of the result elements. Depending on the query root and configuration, this may be a persistent object, aDataRow, a scalar or anObject[].
Template Script
SQLTemplate stores a dynamic template for the SQL query that supports parameters and customization using Velocity scripting language. The most straightforward use of scripting abilities is to build parameterized queries. For example:
SELECT ID, NAME FROM SOME_TABLE WHERE NAME LIKE $a
For advanced scripting options see "Scripting SQLTemplate" chapter in the User Guide.
Per-Database Template Customization
SQLTemplate has a default template script, but
also it allows to configure multiple templates and switch them dynamically.
This way a single query can have multiple "dialects" specific to a given
database.
- Since:
- 1.1
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected CapsStrategyprotected Stringprotected SQLResultprotected booleanprotected ObjectThe root object of this query. -
Constructor Summary
ConstructorsConstructorDescriptionCreates an empty SQLTemplate.SQLTemplate(Class<?> rootClass, String defaultTemplate) SQLTemplate(String defaultTemplate, boolean isFetchingDataRows) Creates a SQLTemplate without an explicit root.SQLTemplate(String objEntityName, String defaultTemplate) SQLTemplate(DataMap rootMap, String defaultTemplate, boolean isFetchingDataRows) SQLTemplate(DbEntity rootEntity, String defaultTemplate) SQLTemplate(ObjEntity rootEntity, String defaultTemplate) -
Method Summary
Modifier and TypeMethodDescriptionaddPrefetch(String prefetchPath) Adds a prefetch.voidaddPrefetch(PrefetchTreeNode prefetchElement) Adds a prefetch with specified relationship path to the query.voidaddPrefetches(Collection<String> prefetches) Adds all prefetches from a provided collection.voidClears all prefetches.createSQLAction(SQLActionVisitor visitor) Calls sqlAction(this) on the visitor.Returns a column name capitalization policy applied to selecting queries.getCustomTemplate(String key) Returns template for key, or null if there is no template configured for this key.Returns a name of the DataNode to use with this SQLTemplate.Returns default SQL template for this query.intintgetMetaData(EntityResolver resolver) Returns query runtime parameters.intUtility method to get the first set of parameters, since most queries will only have one.Returns a map of named parameters that will be bound to SQL.Returns a list of positional parameters that will be bound to SQL.intgetRoot()Returns the root of this query.intgetTemplate(String key) Returns a template for key, or a default template if a template for key is not found.Returns a collection of configured template keys.booleanbooleanbooleanReturns an iterator over parameter sets.intReturns the number of parameter sets.queryWithParameters(Map<String, ?>... parameters) Returns a new query built using this query as a prototype and a new set of parameters.voidremovePrefetch(String prefetch) voidremoveTemplate(String key) voidroute(QueryRouter router, EntityResolver resolver, Query substitutedQuery) A callback method invoked by Cayenne during the routing phase of the query execution.selectFirst(ObjectContext context) Selects a single object using provided context.voidsetCacheGroup(String cacheGroup) voidsetCacheStrategy(QueryCacheStrategy strategy) voidsetColumnNamesCapitalization(CapsStrategy columnNameCapitalization) Sets a column name capitalization policy applied to selecting queries.voidsetDataNodeName(String dataNodeName) Sets a name of the DataNode to use with this SQLTemplate.voidsetDefaultTemplate(String string) Sets default SQL template for this query.voidsetFetchingDataRows(boolean flag) voidsetFetchLimit(int fetchLimit) voidsetFetchOffset(int fetchOffset) voidsetPageSize(int pageSize) voidsetParameters(Map<String, ?>... parameters) Utility method to initialize query with one or more sets of parameters.voidInitializes named parameter of this query.voidsetParamsArray(Object... params) Initializes positional parameters of the query.voidsetParamsList(List<Object> params) Initializes positional parameters of the query.voidsetQueryTimeout(int queryTimeout) Sets query timeout.voidSets an optional explicit mapping of the result set.voidsetResultColumnsTypes(Class<?>... types) voidsetResultColumnsTypes(List<Class<?>> resultColumnsTypes) voidsetResultMapper(Function<?, ?> resultMapper) voidsetReturnGeneratedKeys(boolean returnGeneratedKeys) Sets flag to return generated keys.voidSets the root of the query.voidsetStatementFetchSize(int size) Sets statement's fetch size (0 for no default size)voidsetTemplate(String key, String template) Adds a SQL template string for a given key.voidsetUseScalar(boolean useScalar) Sets flag to use scalars.toString()voidDeprecated, for removal: This API element is subject to removal in a future version.voiduseLocalCache(String cacheGroup) Deprecated, for removal: This API element is subject to removal in a future version.voidDeprecated, for removal: This API element is subject to removal in a future version.voiduseSharedCache(String cacheGroup) Deprecated, for removal: This API element is subject to removal in a future version.
-
Field Details
-
defaultTemplate
-
templates
-
parameters
-
positionalParams
-
columnNamesCapitalization
-
result
-
returnGeneratedKeys
protected boolean returnGeneratedKeys -
root
The root object of this query. May be an entity name, Java class, ObjEntity or DbEntity, depending on how the query was constructed. Null root is allowed.
-
-
Constructor Details
-
SQLTemplate
public SQLTemplate()Creates an empty SQLTemplate. Note this constructor does not specify the "root" of the query, so a user must call "setRoot" later to make sure SQLTemplate can be executed.- Since:
- 1.2
-
SQLTemplate
Creates a SQLTemplate without an explicit root.- Since:
- 4.0
-
SQLTemplate
-
SQLTemplate
-
SQLTemplate
-
SQLTemplate
-
SQLTemplate
-
-
Method Details
-
setResultColumnsTypes
-
getRoot
Returns the root of this query. -
setRoot
Sets the root of the query.- Parameters:
value- The new root- Throws:
IllegalArgumentException- if value is not a String, ObjEntity, DbEntity, Procedure, DataMap, Class or null.
-
toString
-
route
Description copied from interface:QueryA callback method invoked by Cayenne during the routing phase of the query execution. Mapping of DataNodes is provided by QueryRouter. Query should use aQueryRouter.route(DataNode, Query, Query)callback method to route itself. Query can create one or more substitute queries or even provide its own DataNode to execute itself.The default implementation relies on the EntityResolver to find the DataMap based on the query metadata. This mechanism is sufficient for most queries that "know" their root.
-
getMetaData
Description copied from interface:QueryReturns query runtime parameters. The method is called at various stages of the execution by Cayenne access stack to retrieve query parameters. EntityResolver instance is passed to this method, meaning that the query doesn't need to store direct references to Cayenne mapping objects and can resolve them at runtime.- Specified by:
getMetaDatain interfaceQuery- Since:
- 1.2
-
createSQLAction
Calls sqlAction(this) on the visitor.- Specified by:
createSQLActionin interfaceQuery- Since:
- 1.2
-
selectFirst
Description copied from interface:SelectSelects a single object using provided context. The query itself can match any number of objects, but will return only the first one. It returns null if no objects were matched.If it matched more than one object, the first object from the list is returned. This makes 'selectFirst' different from
Select.selectOne(ObjectContext), which would throw in this situation. 'selectFirst' is useful e.g. when the query is ordered and we only want to see the first object (e.g. "most recent news article"), etc.Selecting the first object via "Select.selectFirst(ObjectContext)" is more comprehensible than selecting via "ObjectContext.selectFirst(Select)", because implementations of "Select" set fetch size limit to one.
- Specified by:
selectFirstin interfaceSelect<T>- Since:
- 5.0
-
parametersIterator
-
parametersSize
public int parametersSize()Returns the number of parameter sets. -
setParams
-
setParamsArray
Initializes positional parameters of the query. Parameters are bound in the order they are found in the SQL template. If a given parameter name is used more than once, only the first occurrence is treated as "position", subsequent occurrences are bound with the same value as the first one. If template parameters count is different from the array parameter count, an exception will be thrown.Note that calling this method will reset any previously set *named* parameters.
- Since:
- 4.0
-
setParamsList
Initializes positional parameters of the query. Parameters are bound in the order they are found in the SQL template. If a given parameter name is used more than once, only the first occurrence is treated as "position", subsequent occurrences are bound with the same value as the first one. If template parameters count is different from the list parameter count, an exception will be thrown.Note that calling this method will reset any previously set *named* parameters.
- Since:
- 4.0
-
queryWithParameters
Returns a new query built using this query as a prototype and a new set of parameters. -
getCacheStrategy
- Since:
- 3.0
-
setCacheStrategy
- Since:
- 3.0
-
getCacheGroup
- Since:
- 4.0
-
setCacheGroup
- Since:
- 4.0
-
useLocalCache
Deprecated, for removal: This API element is subject to removal in a future version.- Since:
- 4.0
-
useLocalCache
Deprecated, for removal: This API element is subject to removal in a future version.- Since:
- 4.0
-
getFetchLimit
public int getFetchLimit() -
setFetchLimit
public void setFetchLimit(int fetchLimit) -
getFetchOffset
public int getFetchOffset()- Since:
- 3.0
-
setFetchOffset
public void setFetchOffset(int fetchOffset) - Since:
- 3.0
-
getPageSize
public int getPageSize() -
setPageSize
public void setPageSize(int pageSize) -
setFetchingDataRows
public void setFetchingDataRows(boolean flag) -
isFetchingDataRows
public boolean isFetchingDataRows() -
getDefaultTemplate
Returns default SQL template for this query. -
setDefaultTemplate
Sets default SQL template for this query. -
getTemplate
-
getCustomTemplate
Returns template for key, or null if there is no template configured for this key. UnlikegetTemplate(String)this method does not return a default template as a failover strategy, rather it returns null. -
setTemplate
Adds a SQL template string for a given key. Note the the keys understood by Cayenne must be fully qualified adapter class names. This way the framework can related current DataNode to the right template. E.g. "org.apache.cayenne.dba.oracle.OracleAdapter" is a key that should be used to setup an Oracle-specific template.- See Also:
-
removeTemplate
-
getTemplateKeys
Returns a collection of configured template keys. -
getParams
-
getPositionalParams
-
getParameters
-
setParameters
-
getPrefetchTree
- Since:
- 1.2
-
addPrefetch
-
addPrefetch
Adds a prefetch with specified relationship path to the query.- Since:
- 4.0
-
removePrefetch
- Since:
- 1.2
-
addPrefetches
Adds all prefetches from a provided collection.- Since:
- 1.2
-
clearPrefetches
public void clearPrefetches()Clears all prefetches.- Since:
- 1.2
-
getColumnNamesCapitalization
Returns a column name capitalization policy applied to selecting queries. This is used to simplify mapping of the queries like "SELECT * FROM ...", ensuring that a chosen Cayenne column mapping strategy (e.g. all column names in uppercase) is portable across database engines that can have varying default capitalization. Default (null) value indicates that column names provided in result set are used unchanged.- Since:
- 3.0
-
setColumnNamesCapitalization
Sets a column name capitalization policy applied to selecting queries. This is used to simplify mapping of the queries like "SELECT * FROM ...", ensuring that a chosen Cayenne column mapping strategy (e.g. all column names in uppercase) is portable across database engines that can have varying default capitalization. Default (null) value indicates that column names provided in result set are used unchanged.Note that while a non-default setting is useful for queries that do not rely on a #result directive to describe columns, it works for all SQLTemplates the same way.
- Since:
- 3.0
-
setResult
-
getResult
- Since:
- 3.0
-
setStatementFetchSize
public void setStatementFetchSize(int size) Sets statement's fetch size (0 for no default size)- Since:
- 3.0
-
getStatementFetchSize
public int getStatementFetchSize()- Returns:
- statement's fetch size
- Since:
- 3.0
-
setQueryTimeout
public void setQueryTimeout(int queryTimeout) Sets query timeout.- Since:
- 4.2
-
getQueryTimeout
public int getQueryTimeout()- Returns:
- query timeout
- Since:
- 4.2
-
getDataNodeName
Returns a name of the DataNode to use with this SQLTemplate. This information will be used during query execution if no other routing information is provided such as entity name or class, etc.- Since:
- 4.0
-
setDataNodeName
Sets a name of the DataNode to use with this SQLTemplate. This information will be used during query execution if no other routing information is provided such as entity name or class, etc.- Since:
- 4.0
-
isReturnGeneratedKeys
public boolean isReturnGeneratedKeys()- Returns:
- returnGeneratedKeys flag
- Since:
- 4.1
-
setReturnGeneratedKeys
public void setReturnGeneratedKeys(boolean returnGeneratedKeys) Sets flag to return generated keys.- Since:
- 4.1
-
getResultColumnsTypes
-
setResultColumnsTypes
-
setUseScalar
public void setUseScalar(boolean useScalar) Sets flag to use scalars.- Since:
- 4.1
-
isUseScalar
public boolean isUseScalar() -
setResultMapper
- Since:
- 4.2
-
setCacheStrategy(QueryCacheStrategy)withQueryCacheStrategy.LOCAL_CACHE