KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > amber > field > DependentEntityOneToOneField


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.amber.field;
31
32 import com.caucho.amber.expr.AmberExpr;
33 import com.caucho.amber.expr.DependentEntityOneToOneExpr;
34 import com.caucho.amber.expr.PathExpr;
35 import com.caucho.amber.query.QueryParser;
36 import com.caucho.amber.table.Column;
37 import com.caucho.amber.table.ForeignColumn;
38 import com.caucho.amber.table.LinkColumns;
39 import com.caucho.amber.type.RelatedType;
40 import com.caucho.amber.type.Type;
41 import com.caucho.config.ConfigException;
42 import com.caucho.java.JavaWriter;
43 import com.caucho.log.Log;
44 import com.caucho.util.CharBuffer;
45 import com.caucho.util.L10N;
46
47 import java.io.IOException JavaDoc;
48 import java.util.ArrayList JavaDoc;
49 import java.util.HashSet JavaDoc;
50 import java.util.logging.Logger JavaDoc;
51
52 import javax.persistence.CascadeType;
53
54 /**
55  * Represents a many-to-one link pointing to an entity.
56  */

57 public class DependentEntityOneToOneField extends CascadableField {
58   private static final L10N L = new L10N(DependentEntityOneToOneField.class);
59   protected static final Logger JavaDoc log = Log.open(DependentEntityOneToOneField.class);
60
61   private EntityManyToOneField _targetField;
62   private long _targetLoadIndex;
63   private boolean _isCascadeDelete;
64
65   public DependentEntityOneToOneField(RelatedType relatedType,
66                                       String JavaDoc name)
67     throws ConfigException
68   {
69     super(relatedType, name, null);
70   }
71
72   /**
73    * Sets the target field.
74    */

75   public void setTargetField(EntityManyToOneField targetField)
76   {
77     _targetField = targetField;
78   }
79
80   /**
81    * Sets the target field.
82    */

83   public EntityManyToOneField getTargetField()
84   {
85     return _targetField;
86   }
87
88   /**
89    * Returns the source type as
90    * entity or mapped-superclass.
91    */

92   public RelatedType getEntitySourceType()
93   {
94     return (RelatedType) getSourceType();
95   }
96
97   /**
98    * Returns the target type as
99    * entity or mapped-superclass.
100    */

101   public RelatedType getEntityTargetType()
102   {
103     return (RelatedType) _targetField.getSourceType();
104   }
105
106   /**
107    * Returns the target type.
108    */

109   public Type getType()
110   {
111     return getEntityTargetType();
112   }
113
114   /**
115    * Returns the foreign type.
116    */

117   public String JavaDoc getForeignTypeName()
118   {
119     //return ((KeyColumn) getColumn()).getType().getForeignTypeName();
120
return getEntityTargetType().getForeignTypeName();
121   }
122
123   /**
124    * Sets the column.
125    */

126   public void setColumn(Column column)
127   {
128     throw new IllegalStateException JavaDoc();
129   }
130
131   /**
132    * Sets the cascade-delete property.
133    */

134   public void setCascadeDelete(boolean isCascadeDelete)
135   {
136     _isCascadeDelete = isCascadeDelete;
137   }
138
139   /**
140    * Returns the cascade-delete property.
141    */

142   public boolean isCascadeDelete()
143   {
144     return _isCascadeDelete;
145   }
146
147   public void init()
148     throws ConfigException
149   {
150     super.init();
151
152     _targetLoadIndex = getEntitySourceType().nextLoadGroupIndex();
153   }
154
155   /**
156    * Creates the expression for the field.
157    */

158   public AmberExpr createExpr(QueryParser parser, PathExpr parent)
159   {
160     return new DependentEntityOneToOneExpr(parent,
161                                            _targetField.getLinkColumns());
162   }
163
164   /**
165    * Gets the column corresponding to the target field.
166    */

167   public ForeignColumn getColumn(IdField targetField)
168   {
169     /*
170       EntityColumn entityColumn = (EntityColumn) getColumn();
171
172       ArrayList<ForeignColumn> columns = entityColumn.getColumns();
173
174       Id id = getEntityTargetType().getId();
175       ArrayList<IdField> keys = id.getKeys();
176
177       for (int i = 0; i < keys.size(); i++ ){
178       if (keys.get(i) == targetField)
179       return columns.get(i);
180       }
181     */

182
183     return null;
184   }
185
186   /**
187    * Generates the flush check for this child.
188    */

189   public boolean generateFlushCheck(JavaWriter out)
190     throws IOException JavaDoc
191   {
192     String JavaDoc getter = generateSuperGetter();
193
194     out.println("if (" + getter + " != null) {");
195     out.pushDepth();
196     out.println("int state = ((com.caucho.amber.entity.Entity) " + getter + ").__caucho_getEntityState();");
197
198     // jpa/0s2d
199
out.println("if (this.__caucho_state < com.caucho.amber.entity.Entity.P_DELETING");
200     out.println(" && (state <= com.caucho.amber.entity.Entity.P_NEW || ");
201     out.println(" state >= com.caucho.amber.entity.Entity.P_DELETED))");
202
203     String JavaDoc errorString = ("(\"amber flush: unable to flush " +
204                           getEntitySourceType().getName() + "[\" + __caucho_getPrimaryKey() + \"] "+
205                           "with non-managed dependent relationship one-to-one to "+
206                           getEntityTargetType().getName() + "\")");
207
208     out.println(" throw new IllegalStateException" + errorString + ";");
209     out.popDepth();
210     out.println("}");
211
212     return true;
213   }
214
215   /**
216    * Generates any prologue.
217    */

218   public void generatePrologue(JavaWriter out, HashSet JavaDoc<Object JavaDoc> completedSet)
219     throws IOException JavaDoc
220   {
221     super.generatePrologue(out, completedSet);
222
223     out.println();
224
225     Id id = getEntityTargetType().getId();
226
227     id.generatePrologue(out, completedSet, getName());
228   }
229
230   /**
231    * Generates the linking for a join
232    */

233   public void generateJoin(CharBuffer cb,
234                            String JavaDoc sourceTable,
235                            String JavaDoc targetTable)
236   {
237     LinkColumns linkColumns = _targetField.getLinkColumns();
238
239     cb.append(linkColumns.generateJoin(sourceTable, targetTable));
240   }
241
242   /**
243    * Generates loading code
244    */

245   public int generateLoad(JavaWriter out, String JavaDoc rs,
246                           String JavaDoc indexVar, int index)
247     throws IOException JavaDoc
248   {
249     if (isLazy()) {
250       out.println(generateSuperSetter("null") + ";");
251
252       String JavaDoc loadVar = "__caucho_loadMask_" + (_targetLoadIndex / 64);
253       long loadMask = (1L << _targetLoadIndex);
254
255       out.println(loadVar + " &= ~" + loadMask + "L;");
256     }
257
258     // return index + 1;
259
return index;
260   }
261
262   /**
263    * Generates loading code
264    */

265   public int generateLoadEager(JavaWriter out, String JavaDoc rs,
266                                String JavaDoc indexVar, int index)
267     throws IOException JavaDoc
268   {
269     if (! isLazy()) {
270
271       String JavaDoc loadVar = "__caucho_loadMask_" + (_targetLoadIndex / 64);
272       long loadMask = 1L << (_targetLoadIndex % 64);
273
274       out.println(loadVar + " |= " + loadMask + "L;");
275
276       String JavaDoc javaType = getJavaTypeName();
277
278       out.println("if ((preloadedProperties == null) || (! preloadedProperties.containsKey(\"" + getName() + "\"))) {");
279       out.pushDepth();
280
281       String JavaDoc indexS = "_" + (_targetLoadIndex / 64);
282       indexS += "_" + (1L << (_targetLoadIndex % 64));
283
284       generateLoadProperty(out, indexS, "aConn");
285
286       out.popDepth();
287       out.println("} else {");
288       out.println(" " + generateSuperSetter("(" + javaType + ") preloadedProperties.get(\"" + getName() + "\")") + ";");
289       out.println("}");
290     }
291
292     return index;
293   }
294
295   /**
296    * Generates the set property.
297    */

298   public void generateGetProperty(JavaWriter out)
299     throws IOException JavaDoc
300   {
301     String JavaDoc loadVar = "__caucho_loadMask_" + (_targetLoadIndex / 64);
302     long loadMask = 1L << (_targetLoadIndex % 64);
303
304     String JavaDoc index = "_" + (_targetLoadIndex / 64);
305     index += "_" + (1L << (_targetLoadIndex % 64));
306
307     String JavaDoc javaType = getJavaTypeName();
308
309     out.println();
310     out.println("public " + javaType + " " + getGetterName() + "()");
311     out.println("{");
312     out.pushDepth();
313
314     out.print("if (__caucho_session != null && ");
315     out.println("(" + loadVar + " & " + loadMask + "L) == 0) {");
316     out.pushDepth();
317     out.println("__caucho_load_" + getLoadGroupIndex() + "(__caucho_session);");
318     out.println(loadVar + " |= " + loadMask + "L;");
319
320     generateLoadProperty(out, index, "__caucho_session");
321
322     /*
323       out.print(javaType + " v = (" + javaType + ") __caucho_session.loadProxy(\"" + getEntityTargetType().getName() + "\", ");
324       out.println("__caucho_field_" + getName() + ", true);");
325     */

326
327     out.println("return v"+index+";");
328     out.popDepth();
329     out.println("}");
330     out.println("else {");
331     out.println(" return " + generateSuperGetter() + ";");
332     out.println("}");
333
334     out.popDepth();
335     out.println("}");
336   }
337
338   /**
339    * Generates the set property.
340    */

341   public void generateLoadProperty(JavaWriter out,
342                                    String JavaDoc index,
343                                    String JavaDoc session)
344     throws IOException JavaDoc
345   {
346     String JavaDoc javaType = getJavaTypeName();
347
348     out.println(javaType + " v"+index+" = null;");
349
350     out.println("try {");
351     out.pushDepth();
352
353     out.print("String sql"+index+" = \"");
354     out.print("SELECT o." + getName() +
355               " FROM " + getEntitySourceType().getName() + " o" +
356               " WHERE ");
357
358     ArrayList JavaDoc<IdField> sourceKeys = getEntitySourceType().getId().getKeys();
359     for (int i = 0; i < sourceKeys.size(); i++) {
360       if (i != 0)
361         out.print(" and ");
362
363       IdField key = sourceKeys.get(i);
364
365       out.print("o." + key.getName() + "=?");
366     }
367     out.println("\";");
368
369     out.println("com.caucho.amber.AmberQuery query"+index+" = "+session+".prepareQuery(sql"+index+");");
370
371     out.println("int index"+index+" = 1;");
372
373     getEntitySourceType().getId().generateSet(out, "query"+index, "index"+index, "super");
374
375     out.println("v"+index+" = (" + javaType + ") query"+index+".getSingleResult();");
376
377     out.popDepth();
378     out.println("} catch (java.sql.SQLException e) {");
379     out.println(" throw new RuntimeException(e);");
380     out.println("}");
381
382     out.println(generateSuperSetter("v"+index) + ";");
383   }
384
385   /**
386    * Updates the cached copy.
387    */

388   public void generateCopyUpdateObject(JavaWriter out,
389                                        String JavaDoc dst, String JavaDoc src,
390                                        int updateIndex)
391     throws IOException JavaDoc
392   {
393     if (getIndex() == updateIndex) {
394       String JavaDoc value = generateGet(src);
395       out.println(generateSet(dst, value) + ";");
396     }
397   }
398
399   /**
400    * Updates the cached copy.
401    */

402   public void generateCopyLoadObject(JavaWriter out,
403                                      String JavaDoc dst, String JavaDoc src,
404                                      int updateIndex)
405     throws IOException JavaDoc
406   {
407     if (getLoadGroupIndex() == updateIndex) {
408       String JavaDoc value = generateGet(src);
409       out.println(generateSet(dst, value) + ";");
410     }
411   }
412
413   /**
414    * Generates the set property.
415    */

416   public void generateSetProperty(JavaWriter out)
417     throws IOException JavaDoc
418   {
419     Id id = getEntityTargetType().getId();
420
421     String JavaDoc keyType = getEntityTargetType().getId().getForeignTypeName();
422
423     out.println();
424     out.println("public void " + getSetterName() + "(" + getJavaTypeName() + " v)");
425     out.println("{");
426     out.pushDepth();
427
428     out.println(generateSuperSetter("v") + ";");
429     out.println("if (__caucho_session != null) {");
430     out.pushDepth();
431
432     String JavaDoc updateVar = "__caucho_updateMask_" + (_targetLoadIndex / 64);
433     long updateMask = (1L << _targetLoadIndex);
434
435     out.println(updateVar + " |= " + updateMask + "L;");
436     out.println("__caucho_session.update(this);");
437     out.popDepth();
438     out.println("}");
439
440     out.popDepth();
441     out.println("}");
442   }
443
444   /**
445    * Generates the set clause.
446    */

447   public void generateSet(JavaWriter out, String JavaDoc pstmt, String JavaDoc index)
448     throws IOException JavaDoc
449   {
450   }
451
452   /**
453    * Generates loading cache
454    */

455   public void generateUpdateFromObject(JavaWriter out, String JavaDoc obj)
456     throws IOException JavaDoc
457   {
458   }
459
460   /**
461    * Generates code for foreign entity create/delete
462    */

463   public void generateInvalidateForeign(JavaWriter out)
464     throws IOException JavaDoc
465   {
466     out.println("if (\"" + getEntityTargetType().getTable().getName() + "\".equals(table)) {");
467     out.pushDepth();
468     String JavaDoc loadVar = "__caucho_loadMask_" + (_targetLoadIndex / 64);
469     out.println(loadVar + " = 0;");
470     out.popDepth();
471     out.println("}");
472   }
473 }
474
Popular Tags