| Title: Queries Stored in DataMap |
| |
| |
| |
| <P>To facilitate reuse of queries users can assign symbolic names to them and store such named queries in a DataMap. Normally this is done by <A href="modeling-queries.html" title="Modeling Queries">creating a query in CayenneModeler</A>. Storing queries in a DataMap reduces the amount of code and speeds up query creation process.</P> |
| |
| <P>This example shows how to get a shared instance of a stored query, and use it as a template for customized query.</P> |
| <DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent"> |
| <PRE class="code-java">DataContext context = ... <SPAN class="code-comment">// assume <SPAN class="code-keyword">this</SPAN> exists |
| </SPAN> |
| <SPAN class="code-comment">// 1. lookup prototype |
| </SPAN> |
| <SPAN class="code-comment">// note a <SPAN class="code-keyword">cast</SPAN> to SelectQuery... Generally DataMap can store any type of queries |
| </SPAN>SelectQuery prototype = (SelectQuery) context.getEntityResolver().lookupQuery(<SPAN class="code-quote">"MySelect"</SPAN>); |
| |
| <SPAN class="code-comment">// 2. customize query |
| </SPAN>Map params = <SPAN class="code-keyword">new</SPAN> HashMap(); |
| params.put(<SPAN class="code-quote">"aname"</SPAN>, <SPAN class="code-quote">"Monet"</SPAN>); |
| SelectQuery query = prototype.queryWithParameters(params); |
| |
| <SPAN class="code-comment">// 3. execute query |
| </SPAN>List objects = context.performQuery(query); |
| </PRE> |
| </DIV></DIV> |
| <P>DataContext supports running a named query with preset parameters directly:</P> |
| <DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent"> |
| <PRE class="code-java">DataContext context = ... <SPAN class="code-comment">// assume <SPAN class="code-keyword">this</SPAN> exists |
| </SPAN> |
| <SPAN class="code-comment">// <SPAN class="code-quote">"<SPAN class="code-keyword">false</SPAN>"</SPAN> indicates that a cached result should be used <SPAN class="code-keyword">if</SPAN> available |
| </SPAN>List objects = context.performQuery(<SPAN class="code-quote">"MySelect"</SPAN>, <SPAN class="code-keyword">false</SPAN>); |
| </PRE> |
| </DIV></DIV> |