KickJava   Java API By Example, From Geeks To Geeks.

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


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.ManyToOneExpr;
34 import com.caucho.amber.expr.OneToManyExpr;
35 import com.caucho.amber.expr.PathExpr;
36 import com.caucho.amber.query.QueryParser;
37 import com.caucho.amber.table.LinkColumns;
38 import com.caucho.amber.table.Table;
39 import com.caucho.amber.type.RelatedType;
40 import com.caucho.amber.type.Type;
41 import com.caucho.bytecode.JField;
42 import com.caucho.bytecode.JType;
43 import com.caucho.config.ConfigException;
44 import com.caucho.java.JavaWriter;
45 import com.caucho.log.Log;
46 import com.caucho.util.CharBuffer;
47 import com.caucho.util.L10N;
48
49 import javax.persistence.CascadeType;
50 import java.io.IOException JavaDoc;
51 import java.util.ArrayList JavaDoc;
52 import java.util.Map JavaDoc;
53 import java.util.Set JavaDoc;
54 import java.util.logging.Logger JavaDoc;
55
56 /**
57  * Configuration for a bean's field
58  */

59 public class EntityManyToManyField extends AssociationField {
60   private static final L10N L = new L10N(EntityManyToManyField.class);
61   protected static final Logger JavaDoc log = Log.open(EntityManyToManyField.class);
62
63   private String JavaDoc _mapKey;
64
65   private RelatedType _targetType;
66
67   private Table _associationTable;
68
69   private LinkColumns _sourceLink;
70   private LinkColumns _targetLink;
71
72   private ArrayList JavaDoc<String JavaDoc> _orderByFields;
73   private ArrayList JavaDoc<Boolean JavaDoc> _orderByAscending;
74
75   public EntityManyToManyField(RelatedType relatedType,
76                                String JavaDoc name,
77                                CascadeType[] cascadeTypes)
78     throws ConfigException
79   {
80     super(relatedType, name, cascadeTypes);
81   }
82
83   public EntityManyToManyField(RelatedType relatedType,
84                                String JavaDoc name)
85     throws ConfigException
86   {
87     this(relatedType, name, null);
88   }
89
90   public EntityManyToManyField(RelatedType relatedType)
91   {
92     super(relatedType);
93   }
94
95   public EntityManyToManyField(RelatedType relatedType,
96                                String JavaDoc name,
97                                EntityManyToManyField source,
98                                CascadeType[] cascadeTypes)
99     throws ConfigException
100   {
101     super(relatedType, name, cascadeTypes);
102
103     _targetType = source.getEntitySourceType();
104     _associationTable = source._associationTable;
105     _sourceLink = source._targetLink;
106     _targetLink = source._sourceLink;
107   }
108
109   /**
110    * Gets the map key.
111    */

112   public String JavaDoc getMapKey()
113   {
114     return _mapKey;
115   }
116
117   /**
118    * Sets the map key.
119    */

120   public void setMapKey(String JavaDoc mapKey)
121   {
122     _mapKey = mapKey;
123   }
124
125   /**
126    * Sets the target type.
127    */

128   public void setType(Type targetType)
129   {
130     _targetType = (RelatedType) targetType;
131
132     super.setType(targetType);
133   }
134
135   /**
136    * Returns the source type as
137    * entity or mapped-superclass.
138    */

139   public RelatedType getEntitySourceType()
140   {
141     return (RelatedType) getSourceType();
142   }
143
144   /**
145    * Returns the target type.
146    */

147   public RelatedType getTargetType()
148   {
149     return _targetType;
150   }
151
152   /**
153    * Returns the association table
154    */

155   public Table getAssociationTable()
156   {
157     return _associationTable;
158   }
159
160   /**
161    * Sets the association table
162    */

163   public void setAssociationTable(Table table)
164   {
165     _associationTable = table;
166   }
167
168   /**
169    * Adds a column from the association table to the source side.
170    */

171   public void setSourceLink(LinkColumns link)
172   {
173     _sourceLink = link;
174   }
175
176   /**
177    * Returns the source link.
178    */

179   public LinkColumns getSourceLink()
180   {
181     return _sourceLink;
182   }
183
184   /**
185    * Adds a column from the association table to the target side.
186    */

187   public void setTargetLink(LinkColumns link)
188   {
189     _targetLink = link;
190   }
191
192   /**
193    * Returns the target link.
194    */

195   public LinkColumns getTargetLink()
196   {
197     return _targetLink;
198   }
199
200   /**
201    * Sets the order by.
202    */

203   public void setOrderBy(ArrayList JavaDoc<String JavaDoc> orderByFields,
204                          ArrayList JavaDoc<Boolean JavaDoc> orderByAscending)
205   {
206     _orderByFields = orderByFields;
207     _orderByAscending = orderByAscending;
208   }
209
210   /**
211    * Initializes the field.
212    */

213   public void init()
214     throws ConfigException
215   {
216     // XXX: might not have cascade delete if there's an associated entity
217

218     _targetLink.setSourceCascadeDelete(true);
219     _sourceLink.setSourceCascadeDelete(true);
220   }
221
222   /**
223    * Generates the set clause.
224    */

225   public void generateSet(JavaWriter out, String JavaDoc pstmt,
226                           String JavaDoc obj, String JavaDoc index)
227     throws IOException JavaDoc
228   {
229   }
230
231   /**
232    * Generates the select clause.
233    */

234   public String JavaDoc generateLoadSelect(String JavaDoc id)
235   {
236     return null;
237   }
238
239   /**
240    * Creates the expression for the field.
241    */

242   public AmberExpr createExpr(QueryParser parser, PathExpr parent)
243   {
244     return new ManyToOneExpr(new OneToManyExpr(parser, parent, _sourceLink),
245                              _targetLink);
246   }
247
248   /**
249    * Updates from the cached copy.
250    */

251   public void generateCopyLoadObject(JavaWriter out,
252                                      String JavaDoc dst, String JavaDoc src,
253                                      int loadIndex)
254     throws IOException JavaDoc
255   {
256   }
257
258   /**
259    * Generates the target select.
260    */

261   public String JavaDoc generateTargetSelect(String JavaDoc id)
262   {
263     return getTargetType().getId().generateSelect(id);
264   }
265
266   /**
267    * Generates the select clause.
268    */

269   public String JavaDoc generateTargetLoadSelect(String JavaDoc id)
270   {
271     CharBuffer cb = CharBuffer.allocate();
272
273     cb.append(getTargetType().getId().generateLoadSelect(id));
274
275     String JavaDoc value = getTargetType().generateLoadSelect(id);
276
277     if (cb.length() > 0 && value.length() > 0)
278       cb.append(", ");
279
280     cb.append(value);
281
282     return cb.close();
283   }
284
285   /**
286    * Generates the set property.
287    */

288   public void generateGetProperty(JavaWriter out)
289     throws IOException JavaDoc
290   {
291     String JavaDoc var = "_caucho_field_" + getGetterName();
292
293     boolean isSet = getJavaType().isAssignableTo(Set JavaDoc.class);
294     boolean isMap = false;
295     if (!isSet) {
296       isMap = getJavaType().isAssignableTo(Map JavaDoc.class);
297     }
298
299     JType type = getJavaType();
300     JType []paramArgs = type.getActualTypeArguments();
301     JType param = paramArgs.length > 0 ? paramArgs[0] : null;
302     JType param2 = paramArgs.length > 1 ? paramArgs[1] : null;
303
304     String JavaDoc s = "private ";
305
306     String JavaDoc collectionImpl;
307
308     if (isSet)
309       collectionImpl = "com.caucho.amber.collection.SetImpl";
310     else if (isMap)
311       collectionImpl = "com.caucho.amber.collection.MapImpl";
312     else
313       collectionImpl = "com.caucho.amber.collection.CollectionImpl";
314
315     s = s + collectionImpl;
316
317     if (param != null) {
318       s = s + '<' + param.getPrintName();
319       if (isMap) {
320         if (param2 != null) {
321           s = s + ", " + param2.getPrintName();
322         }
323       }
324       s = s + '>';
325     }
326
327     s = s + " " + var;
328
329     // jpa/0i5g
330
out.println("java.util.HashSet<" + getTargetType().getBeanClass().getName() + "> " + var + "_added;");
331
332     out.println();
333     out.println(s + ';');
334
335     out.println();
336     out.println("public " + getJavaTypeName() + " " + getGetterName() + "()");
337     out.println("{");
338     out.pushDepth();
339
340     out.println("if (" + var + " != null) {");
341     out.pushDepth();
342     out.println(var + ".setSession(__caucho_session);");
343     out.println("return " + var + ";");
344     out.popDepth();
345     out.println("}");
346
347     out.println("if (__caucho_session == null) {");
348     if (! isAbstract()) {
349       out.println(" return super." + getGetterName() + "();");
350     }
351     out.println("}");
352
353     out.println("try {");
354     out.pushDepth();
355
356     out.print("String sql=\"");
357
358     out.print("SELECT c");
359     out.print(" FROM " + getSourceType().getName() + " o,");
360     out.print(" IN(o." + getName() + ") c");
361     out.print(" WHERE ");
362     out.print(getEntitySourceType().getId().generateRawWhere("o"));
363
364     if (_orderByFields != null) {
365       out.print(" ORDER BY ");
366
367       for (int i = 0; i < _orderByFields.size(); i++) {
368         if (i != 0)
369           out.print(", ");
370
371         out.print("c." + _orderByFields.get(i));
372         if (Boolean.FALSE.equals(_orderByAscending.get(i)))
373           out.print(" DESC");
374       }
375     }
376
377     out.println("\";");
378     out.println("com.caucho.amber.AmberQuery query;");
379     out.println("query = __caucho_session.prepareQuery(sql);");
380
381     out.println("int index = 1;");
382     getEntitySourceType().getId().generateSet(out, "query", "index", "this");
383
384     // Ex: _caucho_getChildren = new com.caucho.amber.collection.CollectionImpl
385
out.print(var);
386     out.print(" = new ");
387     out.print(collectionImpl);
388
389     if (param != null) {
390       out.print("<");
391       out.print(param.getPrintName());
392       if (isMap) {
393         out.print(", ");
394         out.print(param2.getPrintName());
395       }
396       out.print(">");
397     }
398
399     out.print("(query");
400     if (isMap) {
401       out.println(",");
402       out.pushDepth();
403       out.print(getTargetType().getBeanClass().getName());
404       out.print(".class.getDeclaredMethod(\"get");
405       String JavaDoc getterMapKey = getMapKey();
406       getterMapKey = Character.toUpperCase(getterMapKey.charAt(0)) + getterMapKey.substring(1);
407       out.print(getterMapKey); // "getId");
408
out.print("\", null)");
409       out.popDepth();
410     }
411     out.println(");");
412
413     /*
414       out.pushDepth();
415
416       generateAdd(out);
417       generateRemove(out);
418       generateClear(out);
419       // generateSize(out);
420
421       out.popDepth();
422       out.println("};");
423     */

424
425     out.println();
426
427     // jpa/0i5g
428
out.print(var + "_added = ");
429     out.println("new java.util.HashSet<" + getTargetType().getBeanClass().getName() + ">();");
430
431     if (isMap)
432       out.print(var + "_added.addAll(" + var + ".values());");
433     else
434       out.println(var + "_added.addAll(" + var + ");");
435
436     out.println();
437     out.println("return " + var + ";");
438
439     out.popDepth();
440     out.println("} catch (Exception e) {");
441     out.println(" throw com.caucho.amber.AmberRuntimeException.create(e);");
442     out.println("}");
443
444     out.popDepth();
445     out.println("}");
446
447     generateAmberAdd(out);
448     generateAmberRemove(out);
449     generateAmberRemoveTargetAll(out);
450   }
451
452
453   /**
454    * Generates the set property.
455    */

456   private void generateAdd(JavaWriter out)
457     throws IOException JavaDoc
458   {
459     JType type = getJavaType();
460     JType []paramArgs = type.getActualTypeArguments();
461     String JavaDoc gType = paramArgs.length > 0 ? paramArgs[0].getPrintName() : "Object";
462
463     out.println("public boolean add(" + gType + " o)");
464     out.println("{");
465     out.pushDepth();
466
467     String JavaDoc ownerType = getEntitySourceType().getInstanceClassName();
468
469     out.println("if (! (o instanceof " + ownerType + "))");
470     out.println(" throw new java.lang.IllegalArgumentException((o == null ? \"null\" : o.getClass().getName()) + \" must be a " + ownerType + "\");");
471
472     out.println(ownerType + " bean = (" + ownerType + ") o;");
473
474     // XXX: makePersistent
475

476     /*
477       ArrayList<Column> keyColumns = getKeyColumns();
478       for (int i = 0; i < keyColumns.size(); i++) {
479       Column column = keyColumns.get(i);
480       AbstractProperty prop = column.getProperty();
481
482
483       if (prop != null) {
484       out.println("bean." + prop.getSetterName() + "(" + ownerType + "__ResinExt.this);");
485       }
486       }
487     */

488
489     out.println("return true;");
490
491     out.popDepth();
492     out.println("}");
493   }
494
495   /**
496    * Generates the set property.
497    */

498   private void generateRemove(JavaWriter out)
499     throws IOException JavaDoc
500   {
501     JType type = getJavaType();
502     JType []paramArgs = type.getActualTypeArguments();
503     String JavaDoc gType = paramArgs.length > 0 ? paramArgs[0].getPrintName() : "Object";
504
505     out.println("public boolean remove(" + gType + " o)");
506     out.println("{");
507     out.pushDepth();
508
509     String JavaDoc ownerType = getSourceType().getInstanceClassName();
510
511     out.println("if (! (o instanceof " + ownerType + "))");
512     out.println(" throw new java.lang.IllegalArgumentException((o == null ? \"null\" : o.getClass().getName()) + \" must be a " + ownerType + "\");");
513
514     out.println(ownerType + " bean = (" + ownerType + ") o;");
515
516     // XXX: makePersistent
517

518     /*
519       ArrayList<Column> keyColumns = getKeyColumns();
520       for (int i = 0; i < keyColumns.size(); i++) {
521       Column column = keyColumns.get(i);
522       AbstractProperty prop = column.getProperty();
523
524       if (prop != null) {
525       out.println("bean." + prop.getSetterName() + "(null);");
526       }
527       }
528     */

529
530     out.println("return true;");
531
532     out.popDepth();
533     out.println("}");
534   }
535
536   /**
537    * Generates the clear method.
538    */

539   private void generateClear(JavaWriter out)
540     throws IOException JavaDoc
541   {
542     out.println("public void clear()");
543     out.println("{");
544     out.pushDepth();
545
546     out.println("if (__caucho_session != null) {");
547     out.pushDepth();
548
549     out.println("try {");
550     out.pushDepth();
551
552     out.println("__caucho_session.flushNoChecks();");
553
554     out.print("String sql=\"");
555
556     out.print("UPDATE ");
557     out.print(getSourceType().getName());
558     out.print(" SET ");
559     /*
560       ArrayList<Column> columns = getKeyColumns();
561       for (int i = 0; i < columns.size(); i++) {
562       if (i != 0)
563       out.print(", ");
564
565       out.print(columns.get(i).getName());
566       out.print("=null");
567       }
568     */

569
570     out.print(" WHERE ");
571
572     /*
573       for (int i = 0; i < columns.size(); i++) {
574       if (i != 0)
575       out.print(" and ");
576
577       out.print(columns.get(i).getName());
578       out.print("=?");
579       }
580     */

581
582     out.println("\";");
583     out.println("com.caucho.amber.AmberQuery query;");
584     out.println("query = __caucho_session.prepareQuery(sql);");
585
586     String JavaDoc ownerType = getSourceType().getInstanceClassName();
587
588     out.println("int index = 1;");
589     getEntitySourceType().getId().generateSet(out, "query", "index", ownerType + ".this");
590
591     out.println("query.executeUpdate();");
592
593     out.println("super.clear();");
594
595     out.popDepth();
596     out.println("} catch (java.sql.SQLException e) {");
597     out.println(" throw com.caucho.amber.AmberRuntimeException.create(e);");
598     out.println("}");
599
600     out.popDepth();
601     out.println("} else {");
602     out.println(" super.clear();");
603     out.println("}");
604
605     out.popDepth();
606     out.println("}");
607   }
608
609   /**
610    * Generates the size method.
611    */

612   private void generateSize(JavaWriter out)
613     throws IOException JavaDoc
614   {
615     out.println("public int size()");
616     out.println("{");
617     out.pushDepth();
618
619     out.println("if (__caucho_session == null || isValid())");
620     out.println(" return super.size();");
621
622     out.println("try {");
623     out.pushDepth();
624
625     out.println("__caucho_session.flushNoChecks();");
626
627     out.print("String sql=\"");
628
629     out.print("SELECT count(*) FROM ");
630     out.print(getSourceType().getName());
631     out.print(" AS o ");
632
633     out.print(" WHERE ");
634
635     /*
636       ArrayList<Column> columns = getKeyColumns();
637       for (int i = 0; i < columns.size(); i++) {
638       if (i != 0)
639       out.print(" and ");
640
641       out.print("o." + columns.get(i).getName());
642       out.print("=?");
643       }
644     */

645
646     out.println("\";");
647     out.println("com.caucho.amber.AmberQuery query;");
648     out.println("query = __caucho_session.prepareQuery(sql);");
649
650     out.println("int index = 1;");
651
652     // ejb/06h0
653
getEntitySourceType().getId().generateSet(out, "query", getSourceType().getInstanceClassName() + ".this", "index"); // "__ResinExt.this", "index");
654

655     out.println("java.sql.ResultSet rs = query.executeQuery();");
656
657     out.println("if (rs.next())");
658     out.println(" return rs.getInt(1);");
659     out.println("else");
660     out.println(" return 0;");
661
662     out.popDepth();
663     out.println("} catch (java.sql.SQLException e) {");
664     out.println(" throw com.caucho.amber.AmberRuntimeException.create(e);");
665     out.println("}");
666
667     out.popDepth();
668     out.println("}");
669   }
670
671
672   /**
673    * Generates the (post) cascade operation from
674    * parent to this child. This field will only
675    * be cascaded first if the operation can be
676    * performed with no risk to break FK constraints.
677    */

678   public void generatePostCascade(JavaWriter out,
679                                   String JavaDoc aConn,
680                                   CascadeType cascadeType)
681     throws IOException JavaDoc
682   {
683     if (cascadeType != CascadeType.PERSIST
684         && cascadeType != CascadeType.REMOVE)
685       return;
686
687     if (isCascade(cascadeType)) {
688       out.println("if (__caucho_state <= P_TRANSACTIONAL) {");
689       out.pushDepth();
690
691       String JavaDoc amberCascade = "__amber_" + getGetterName();
692
693       if (cascadeType == CascadeType.PERSIST)
694         amberCascade += "_add";
695       else
696         amberCascade += "_remove";
697
698       String JavaDoc getter = "_caucho_field_" + getGetterName(); // generateSuperGetter();
699

700       out.println("if (" + getter + " != null) {");
701
702       out.println(" for (Object o : " + getter + ")");
703       out.println(" " + amberCascade + "(o);");
704
705       out.println("}");
706
707       out.popDepth();
708       out.println("}");
709     }
710   }
711
712   /**
713    * Generates the set property.
714    */

715   public void generateAmberAdd(JavaWriter out)
716     throws IOException JavaDoc
717   {
718     // commented out: jpa/0s2d
719
// String targetType = getTargetType().getProxyClass().getName();
720

721     String JavaDoc targetType = getTargetType().getInstanceClassName();
722
723     out.println();
724     out.println("public boolean" +
725                 " __amber_" + getGetterName() + "_add(Object o)");
726     out.println("{");
727     out.pushDepth();
728
729     out.println("if (! (o instanceof " + targetType + "))");
730     out.println(" return false;");
731
732     out.println();
733     out.println(targetType + " v = (" + targetType + ") o;");
734
735     // jpa/0i5g
736
String JavaDoc varAdded = "_caucho_field_" + getGetterName() + "_added";
737     out.println();
738     out.println("if (" + varAdded + " == null)");
739     out.println(" " + varAdded + " = new java.util.HashSet<" + getTargetType().getBeanClass().getName() + ">();");
740     out.println("else if (" + varAdded + ".contains(v))");
741     out.println(" return false;");
742     out.println();
743     out.println(varAdded + ".add(v);");
744
745     out.println();
746     out.println("if (__caucho_session == null)");
747     out.println(" return false;");
748
749     out.println();
750     out.print("String sql = \"INSERT INTO ");
751     out.print(_associationTable.getName() + " (");
752
753     out.print(_sourceLink.generateSelectSQL(null));
754
755     out.print(", ");
756
757     out.print(_targetLink.generateSelectSQL(null));
758
759     out.print(") VALUES (");
760
761     int count = (getEntitySourceType().getId().getKeyCount() +
762                  getTargetType().getId().getKeyCount());
763
764     for (int i = 0; i < count; i++) {
765       if (i != 0)
766         out.print(", ");
767
768       out.print("?");
769     }
770     out.println(")\";");
771
772     out.println();
773     out.println("try {");
774     out.pushDepth();
775
776     out.println("java.sql.PreparedStatement pstmt = __caucho_session.prepareInsertStatement(sql);");
777
778     out.println("int index = 1;");
779     getEntitySourceType().getId().generateSet(out, "pstmt", "index", "this");
780     getTargetType().getId().generateSet(out, "pstmt", "index", "v");
781
782     out.println("if (pstmt.executeUpdate() == 1) {");
783     out.pushDepth();
784     out.println("__caucho_session.addCompletion(new com.caucho.amber.entity.TableInvalidateCompletion(\"" + _targetLink.getSourceTable().getName() + "\"));");
785     out.println("return true;");
786     out.popDepth();
787     out.println("}");
788
789     out.popDepth();
790     out.println("} catch (Exception e) {");
791     out.println(" __caucho_log.log(java.util.logging.Level.FINE, e.toString(), e);");
792     out.println("}");
793
794     out.println("return false;");
795     out.popDepth();
796     out.println("}");
797   }
798
799   /**
800    * Generates the remove property.
801    */

802   public void generateAmberRemove(JavaWriter out)
803     throws IOException JavaDoc
804   {
805     // commented out: jpa/0s2d
806
// String targetType = getTargetType().getProxyClass().getName();
807

808     String JavaDoc targetType = getTargetType().getInstanceClassName();
809
810     out.println();
811     out.println("public boolean" +
812                 " __amber_" + getGetterName() + "_remove(Object o)");
813     out.println("{");
814     out.pushDepth();
815
816     out.println("if (! (o instanceof " + targetType + "))");
817     out.println(" return false;");
818
819     out.println();
820     out.println(targetType + " v = (" + targetType + ") o;");
821     out.println();
822     out.println("if (__caucho_session == null)");
823     out.println(" return false;");
824
825     out.println();
826     out.print("String sql = \"DELETE FROM ");
827     out.print(_associationTable.getName() + " WHERE ");
828
829     out.print(_sourceLink.generateMatchArgSQL(null));
830
831     out.print(" and ");
832
833     out.print(_targetLink.generateMatchArgSQL(null));
834
835     out.println("\";");
836
837     out.println();
838     out.println("try {");
839     out.pushDepth();
840
841     out.println("java.sql.PreparedStatement pstmt = __caucho_session.prepareStatement(sql);");
842
843     out.println("int index = 1;");
844     getEntitySourceType().getId().generateSet(out, "pstmt", "index", "this");
845     getTargetType().getId().generateSet(out, "pstmt", "index", "v");
846
847     out.println("if (pstmt.executeUpdate() == 1) {");
848     out.pushDepth();
849     out.println("__caucho_session.addCompletion(new com.caucho.amber.entity.TableInvalidateCompletion(\"" + _targetLink.getSourceTable().getName() + "\"));");
850     out.println("return true;");
851     out.popDepth();
852     out.println("}");
853
854     out.popDepth();
855     out.println("} catch (Exception e) {");
856     out.println(" __caucho_log.log(java.util.logging.Level.FINE, e.toString(), e);");
857     out.println("}");
858
859     out.println("return false;");
860     out.popDepth();
861     out.println("}");
862   }
863
864   /**
865    * Generates the remove property.
866    */

867   public void generateAmberRemoveTargetAll(JavaWriter out)
868     throws IOException JavaDoc
869   {
870     // commented out: jpa/0s2d
871
// String targetType = getTargetType().getProxyClass().getName();
872

873     String JavaDoc targetType = getTargetType().getInstanceClassName();
874
875     out.println();
876     out.println("public boolean" +
877                 " __amber_" + getGetterName() + "_remove_target(Object o)");
878     out.println("{");
879     out.pushDepth();
880
881     out.println("if (! (o instanceof " + targetType + "))");
882     out.println(" return false;");
883
884     out.println();
885     out.println(targetType + " v = (" + targetType + ") o;");
886     out.println();
887     out.println("if (__caucho_session == null)");
888     out.println(" return false;");
889
890     out.println();
891     out.print("String sql = \"DELETE FROM ");
892     out.print(_associationTable.getName() + " WHERE ");
893
894     out.print(_targetLink.generateMatchArgSQL(null));
895
896     out.println("\";");
897
898     out.println();
899     out.println("try {");
900     out.pushDepth();
901
902     out.println("java.sql.PreparedStatement pstmt = __caucho_session.prepareStatement(sql);");
903
904     out.println("int index = 1;");
905     getTargetType().getId().generateSet(out, "pstmt", "index", "v");
906
907     out.println("if (pstmt.executeUpdate() == 1)");
908     out.println(" return true;");
909
910     out.popDepth();
911     out.println("} catch (Exception e) {");
912     out.println(" __caucho_log.log(java.util.logging.Level.FINE, e.toString(), e);");
913     out.println("}");
914
915     out.println("return false;");
916     out.popDepth();
917     out.println("}");
918   }
919
920   /**
921    * Generates the set property.
922    */

923   public void generateSetProperty(JavaWriter out)
924     throws IOException JavaDoc
925   {
926     // commented out: jpa/0s2i
927
// JMethod setter = getSetterMethod();
928
//
929
// if (setter == null)
930
// return;
931
//
932
// JType type = getGetterMethod().getGenericReturnType();
933

934     JType type;
935
936     if (! getSourceType().isFieldAccess()) {
937       type = getGetterMethod().getGenericReturnType();
938     }
939     else {
940       JField field = RelatedType.getField(getBeanClass(), getName());
941       type = field.getGenericType();
942     }
943
944     out.println();
945     // commented out: jpa/0s2i
946
// out.print("public void " + setter.getName() + "(");
947
out.print("public void " + getSetterName() + "(");
948     out.println(type.getPrintName() + " value)");
949     out.println("{");
950     out.pushDepth();
951
952     out.println("if (" + generateSuperGetter() + " == value)");
953     out.println(" return;");
954     out.println();
955
956     //
957
// jpa/0s2j needs to generate the following snippet:
958
//
959
// _caucho___caucho_get_xAnnualReviews
960
// = new com.caucho.amber.collection.CollectionImpl<qa.XAnnualReview>(__caucho_session, null);
961
// _caucho___caucho_get_xAnnualReviews.addAll(0, value);
962
//
963
//
964
// jpa/0s2j:
965

966     out.println("try {");
967     out.pushDepth();
968
969     String JavaDoc var = "_caucho_field_" + getGetterName();
970
971     out.print(var + " = new ");
972
973     type = getJavaType();
974
975     boolean isSet = type.isAssignableTo(Set JavaDoc.class);
976     boolean isMap = false;
977     if (!isSet) {
978       isMap = type.isAssignableTo(Map JavaDoc.class);
979     }
980
981     JType []paramArgs = type.getActualTypeArguments();
982     JType param = paramArgs.length > 0 ? paramArgs[0] : null;
983     JType param2 = paramArgs.length > 1 ? paramArgs[1] : null;
984
985     String JavaDoc collectionImpl;
986
987     if (isSet)
988       collectionImpl = "com.caucho.amber.collection.SetImpl";
989     else if (isMap)
990       collectionImpl = "com.caucho.amber.collection.MapImpl";
991     else
992       collectionImpl = "com.caucho.amber.collection.CollectionImpl";
993
994     out.print(collectionImpl);
995
996     if (param != null) {
997       out.print("<");
998       out.print(param.getPrintName());
999       if (isMap) {
1000        if (param2 != null) {
1001          out.print(", ");
1002          out.print(param2.getPrintName());
1003        }
1004      }
1005      out.print(">");
1006    }
1007
1008    out.print("(__caucho_session, null");
1009    if (isMap) {
1010      out.print(", ");
1011      out.print(getTargetType().getBeanClass().getName());
1012      out.print(".class.getDeclaredMethod(\"get");
1013      String JavaDoc getterMapKey = getMapKey();
1014      getterMapKey = Character.toUpperCase(getterMapKey.charAt(0)) + getterMapKey.substring(1);
1015      out.print(getterMapKey); // "getId");
1016
out.print("\")");
1017    }
1018    out.println(");");
1019
1020    out.print(var + ".");
1021
1022    if (isMap) {
1023      out.println("putAll(value);");
1024    }
1025    else {
1026      out.println("addAll(0, value);");
1027    }
1028
1029    out.popDepth();
1030    out.println("} catch(Exception e) {");
1031    out.println(" throw com.caucho.amber.AmberRuntimeException.create(e);");
1032    out.println("}");
1033
1034    out.popDepth();
1035    out.println("}");
1036  }
1037
1038  /**
1039   * Generates code for foreign entity create/delete
1040   */

1041  public void generateInvalidateForeign(JavaWriter out)
1042    throws IOException JavaDoc
1043  {
1044    out.println("if (\"" + _sourceLink.getSourceTable().getName() + "\".equals(table)) {");
1045    out.pushDepth();
1046
1047    generateExpire(out);
1048
1049    out.popDepth();
1050    out.println("}");
1051  }
1052
1053  /**
1054   * Generates code for the object expire
1055   */

1056  public void generateExpire(JavaWriter out)
1057    throws IOException JavaDoc
1058  {
1059    String JavaDoc var = "_caucho_field_" + getGetterName();
1060
1061    out.println("if (" + var + " != null)");
1062    out.println(" " + var + ".update();");
1063  }
1064}
1065
Popular Tags