KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > oracle > toplink > essentials > queryframework > ResultSetMappingQuery


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the "License"). You may not use this file except
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * HEADER in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21 // Copyright (c) 1998, 2006, Oracle. All rights reserved.
22
package oracle.toplink.essentials.queryframework;
23 import java.util.*;
24
25 import oracle.toplink.essentials.internal.localization.ExceptionLocalization;
26 import oracle.toplink.essentials.exceptions.QueryException;
27 import oracle.toplink.essentials.exceptions.DatabaseException;
28 import oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl;
29 import oracle.toplink.essentials.sessions.DatabaseRecord;
30
31 /**
32  * <p><b>Purpose</b>:
33  * Concrete class to perform read using raw SQL and the SQLResultSetMapping.
34  * <p>
35  * <p><b>Responsibilities</b>:
36  * Execute a selecting raw SQL string.
37  * Returns a List of results. Each item in the list will be another list
38  * consisting of the expected populated return types in the order they were
39  * specified in the SQLResultSetMapping
40  *
41  * @see SQLResultSetMapping
42  * @author Gordon Yorke
43  * @since TopLink Java Essentials
44  */

45
46 public class ResultSetMappingQuery extends ObjectBuildingQuery {
47     
48     protected String JavaDoc resultSetMappingName;
49     
50     protected SQLResultSetMapping resultSetMapping;
51     
52     /**
53      * PUBLIC:
54      * Initialize the state of the query.
55      */

56     public ResultSetMappingQuery() {
57         super();
58    }
59
60     /**
61      * PUBLIC:
62      * Initialize the query to use the specified call.
63      */

64     public ResultSetMappingQuery(Call call) {
65         this();
66         setCall(call);
67     }
68
69     /**
70      * PUBLIC:
71      * Initialize the query to use the specified call and SQLResultSetMapping
72      */

73     public ResultSetMappingQuery(Call call, String JavaDoc sqlResultSetMappingName) {
74         this();
75         setCall(call);
76         this.resultSetMappingName = sqlResultSetMappingName;
77     }
78
79    /**
80      * INTERNAL:
81      * Clone the query.
82      */

83     public Object JavaDoc clone() {
84         ResultSetMappingQuery cloneQuery = (ResultSetMappingQuery)super.clone();
85         cloneQuery.resultSetMapping = this.resultSetMapping;
86         cloneQuery.resultSetMappingName = this.resultSetMappingName;
87         return cloneQuery;
88     }
89
90     /**
91      * INTERNAL:
92      * Convert all the class-name-based settings in this ResultSetMapping to actual class-based
93      * settings. This method is used when converting a project that has been built
94      * with class names to a project with classes.
95      * @param classLoader
96      */

97     public void convertClassNamesToClasses(ClassLoader JavaDoc classLoader){
98         resultSetMapping.convertClassNamesToClasses(classLoader);
99     };
100
101     /**
102      * PUBLIC:
103      * Used to define a store procedure or SQL query.
104      */

105 /* public void setCall(Call call) {
106         if (call instanceof SQLCall){
107             ((SQLCall)call).setSQLString(((SQLCall)call).getCallString().replace('?','#'));
108         }
109         super.setCall(call);
110     }
111 */

112     /**
113      * PUBLIC:
114      * This will be the SQLResultSetMapping that is used by this query to process
115      * the database results
116      */

117     public void setSQLResultSetMapping(SQLResultSetMapping resultSetMapping){
118         this.resultSetMapping = resultSetMapping;
119         this.resultSetMappingName = resultSetMapping.getName();
120     }
121
122     /**
123      * PUBLIC:
124      * This will be the SQLResultSetMapping that is used by this query to process
125      * the database results
126      */

127     public void setSQLResultSetMappingName(String JavaDoc name){
128         if (name == null && this.resultSetMapping == null){
129             throw new IllegalArgumentException JavaDoc(ExceptionLocalization.buildMessage("null_sqlresultsetmapping_in_query"));
130         }
131         this.resultSetMappingName = name;
132         
133     }
134     
135     /**
136      * INTERNAL:
137      * This method is used to build the results. Interpreting the
138      * SQLResultSetMapping.
139      */

140     protected List buildObjectsFromRecords(List databaseRecords){
141         List results = new ArrayList(databaseRecords.size() );
142         SQLResultSetMapping mapping = this.getSQLResultSetMapping();
143         for (Iterator iterator = databaseRecords.iterator(); iterator.hasNext();){
144             if (mapping.getResults().size()>1){
145                 Object JavaDoc[] resultElement = new Object JavaDoc[mapping.getResults().size()];
146                 DatabaseRecord record = (DatabaseRecord)iterator.next();
147                 for (int i = 0;i<mapping.getResults().size();i++){
148                     resultElement[i] = ((SQLResult)mapping.getResults().get(i)).getValueFromRecord(record, this);
149                 }
150                 results.add(resultElement);
151             }else if (mapping.getResults().size()==1) {
152                 DatabaseRecord record = (DatabaseRecord)iterator.next();
153                 results.add( ((SQLResult)mapping.getResults().get(0)).getValueFromRecord(record, this));
154             }else {
155                 return results;
156             }
157         }
158         return results;
159         
160     }
161
162     /**
163      * INTERNAL:
164      * Executes the prepared query on the datastore.
165      */

166     public Object JavaDoc executeDatabaseQuery() throws DatabaseException {
167         if (getSession().isUnitOfWork()) {
168             UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl)getSession();
169
170             // Note if a nested unit of work this will recursively start a
171
// transaction early on the parent also.
172
if ((!unitOfWork.getCommitManager().isActive()) && (!unitOfWork.wasTransactionBegunPrematurely())) {
173                 unitOfWork.beginTransaction();
174                 unitOfWork.setWasTransactionBegunPrematurely(true);
175             }
176             if (unitOfWork.isNestedUnitOfWork()) {
177                 // execute in parent UOW then register normally here.
178
UnitOfWorkImpl nestedUnitOfWork = (UnitOfWorkImpl)getSession();
179                 setSession(nestedUnitOfWork.getParent());
180                 Object JavaDoc result = executeDatabaseQuery();
181                 setSession(nestedUnitOfWork);
182                 Object JavaDoc clone = registerIndividualResult(result, unitOfWork, false, null);
183
184                 if (shouldUseWrapperPolicy()) {
185                     clone = getDescriptor().getObjectBuilder().wrapObject(clone, unitOfWork);
186                 }
187                 return clone;
188             }
189         }
190         session.validateQuery(this);// this will update the query with any settings
191

192         if (getQueryId() == 0) {
193             setQueryId(getSession().getNextQueryId());
194         }
195
196         Vector rows = getQueryMechanism().executeSelect();
197         setExecutionTime(System.currentTimeMillis());
198         // If using 1-m joins, must set all rows.
199
return buildObjectsFromRecords(rows);
200     }
201
202     /**
203      * INTERNAL:
204      * Prepare the receiver for execution in a session.
205      */

206     protected void prepare() {
207         if ((!shouldMaintainCache()) && shouldRefreshIdentityMapResult()) {
208             throw QueryException.refreshNotPossibleWithoutCache(this);
209         }
210
211         getQueryMechanism().prepare();
212
213         getQueryMechanism().prepareExecuteSelect();
214     }
215
216     /**
217      * PUBLIC:
218      * This will be the SQLResultSetMapping that is used by this query to process
219      * the database results
220      */

221     public SQLResultSetMapping getSQLResultSetMapping(){
222         if (this.resultSetMapping == null && this.resultSetMappingName != null){
223             this.resultSetMapping = this.getSession().getProject().getSQLResultSetMapping(this.resultSetMappingName);
224         }
225         return this.resultSetMapping;
226     }
227
228     /**
229      * PUBLIC:
230      * Return the result set mapping name.
231      */

232     public String JavaDoc getSQLResultSetMappingName() {
233         return this.resultSetMappingName;
234     }
235 }
236
Popular Tags