KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > access > FlattenedRelationshipUpdate


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.access;
57
58 import java.util.Collections JavaDoc;
59 import java.util.HashMap JavaDoc;
60 import java.util.Iterator JavaDoc;
61 import java.util.List JavaDoc;
62 import java.util.Map JavaDoc;
63
64 import org.objectstyle.cayenne.CayenneRuntimeException;
65 import org.objectstyle.cayenne.DataObject;
66 import org.objectstyle.cayenne.dba.PkGenerator;
67 import org.objectstyle.cayenne.exp.Expression;
68 import org.objectstyle.cayenne.exp.ExpressionFactory;
69 import org.objectstyle.cayenne.map.DbAttribute;
70 import org.objectstyle.cayenne.map.DbEntity;
71 import org.objectstyle.cayenne.map.DbJoin;
72 import org.objectstyle.cayenne.map.DbRelationship;
73 import org.objectstyle.cayenne.map.ObjRelationship;
74 import org.objectstyle.cayenne.query.SelectQuery;
75
76 /**
77  * A holder of flattened relationship modification data.
78  *
79  * @since 1.2 renamed from FlattenedRelationshipInfo
80  * @author Andrei Adamchik
81  */

82 final class FlattenedRelationshipUpdate extends RelationshipUpdate {
83
84     FlattenedRelationshipUpdate(DataObject source, DataObject destination,
85             ObjRelationship relationship) {
86
87         super(source, destination, relationship);
88     }
89
90     /**
91      * Returns a join DbEntity for the single-step flattened relationship.
92      */

93     DbEntity getJoinEntity() {
94         List JavaDoc relList = relationship.getDbRelationships();
95         if (relList.size() != 2) {
96             throw new CayenneRuntimeException(
97                     "Only single-step flattened relationships are supported in this operation: "
98                             + relationship);
99         }
100
101         DbRelationship firstDbRel = (DbRelationship) relList.get(0);
102         return (DbEntity) firstDbRel.getTargetEntity();
103     }
104
105     /**
106      * Returns a snapshot for the join record for the single-step flattened relationship.
107      */

108     Map JavaDoc buildJoinSnapshot() {
109
110         List JavaDoc relList = relationship.getDbRelationships();
111         if (relList.size() != 2) {
112             throw new CayenneRuntimeException(
113                     "Only single-step flattened relationships are supported in this operation: "
114                             + relationship);
115         }
116
117         DbRelationship firstDbRel = (DbRelationship) relList.get(0);
118         DbRelationship secondDbRel = (DbRelationship) relList.get(1);
119
120         Map JavaDoc sourceId = source.getObjectId().getIdSnapshot();
121         Map JavaDoc destinationId = destination.getObjectId().getIdSnapshot();
122
123         Map JavaDoc snapshot = new HashMap JavaDoc(sourceId.size() + destinationId.size(), 1);
124         List JavaDoc joins = firstDbRel.getJoins();
125         for (int i = 0, numJoins = joins.size(); i < numJoins; i++) {
126             DbJoin join = (DbJoin) joins.get(i);
127             snapshot.put(join.getTargetName(), sourceId.get(join.getSourceName()));
128         }
129
130         joins = secondDbRel.getJoins();
131         for (int i = 0, numJoins = joins.size(); i < numJoins; i++) {
132             DbJoin join = (DbJoin) joins.get(i);
133             snapshot.put(join.getSourceName(), destinationId.get(join.getTargetName()));
134         }
135
136         return snapshot;
137     }
138
139     /**
140      * Returns a snapshot for join record for the single-step flattened relationship,
141      * generating value for the primary key column if it is not propagated via the
142      * relationships.
143      */

144     Map JavaDoc buildJoinSnapshotForInsert() {
145         Map JavaDoc snapshot = buildJoinSnapshot();
146
147         boolean autoPkDone = false;
148         DbEntity joinEntity = getJoinEntity();
149         List JavaDoc pkAttributes = joinEntity.getPrimaryKey();
150         Iterator JavaDoc it = pkAttributes.iterator();
151
152         while (it.hasNext()) {
153             DbAttribute dbAttr = (DbAttribute) it.next();
154             String JavaDoc dbAttrName = dbAttr.getName();
155             if (snapshot.containsKey(dbAttrName)) {
156                 continue;
157             }
158
159             if (autoPkDone) {
160                 throw new CayenneRuntimeException(
161                         "Primary Key autogeneration only works for a single attribute.");
162             }
163
164             // finally, use database generation mechanism
165
try {
166                 DataNode node = source.getDataContext().lookupDataNode(
167                         joinEntity.getDataMap());
168                 PkGenerator pkGenerator = node.getAdapter().getPkGenerator();
169                 Object JavaDoc pkValue = pkGenerator.generatePkForDbEntity(node, joinEntity);
170                 snapshot.put(dbAttrName, pkValue);
171                 autoPkDone = true;
172             }
173             catch (Exception JavaDoc ex) {
174                 throw new CayenneRuntimeException("Error generating PK: "
175                         + ex.getMessage(), ex);
176             }
177         }
178
179         return snapshot;
180     }
181
182     /**
183      * Returns pk snapshots for join records for the single-stp flattened relationship.
184      * Multiple joins between the same pair of objects are theoretically possible, so the
185      * return value is a list.
186      */

187     List JavaDoc buildJoinSnapshotsForDelete() {
188         Map JavaDoc snapshot = buildJoinSnapshot();
189
190         DbEntity joinEntity = getJoinEntity();
191         List JavaDoc pkAttributes = joinEntity.getPrimaryKey();
192         Iterator JavaDoc it = pkAttributes.iterator();
193
194         boolean fetchKey = false;
195         while (it.hasNext()) {
196             DbAttribute dbAttr = (DbAttribute) it.next();
197             String JavaDoc dbAttrName = dbAttr.getName();
198             if (!snapshot.containsKey(dbAttrName)) {
199                 fetchKey = true;
200                 break;
201             }
202         }
203
204         if (!fetchKey) {
205             return Collections.singletonList(snapshot);
206         }
207
208         // ok, the key is not included in snapshot, must do the fetch...
209
// TODO: this should be optimized in the future, but now DeleteBatchQuery
210
// expects a PK snapshot, so we must provide it.
211

212         SelectQuery query = new SelectQuery(joinEntity, ExpressionFactory.matchAllDbExp(
213                 snapshot,
214                 Expression.EQUAL_TO));
215         query.setFetchingDataRows(true);
216
217         it = pkAttributes.iterator();
218         while (it.hasNext()) {
219             DbAttribute dbAttr = (DbAttribute) it.next();
220             query.addCustomDbAttribute(dbAttr.getName());
221         }
222
223         return source.getDataContext().performQuery(query);
224     }
225 }
Popular Tags