1 56 package org.objectstyle.cayenne.access.trans; 57 58 import java.util.ArrayList ; 59 import java.util.Iterator ; 60 import java.util.List ; 61 import java.util.Map ; 62 63 import org.objectstyle.cayenne.ObjectId; 64 import org.objectstyle.cayenne.map.DbAttribute; 65 import org.objectstyle.cayenne.map.DbEntity; 66 import org.objectstyle.cayenne.map.DbRelationship; 67 68 79 public class InsertTranslator extends QueryAssembler { 80 81 protected List columnList = new ArrayList (); 82 83 public String aliasForTable(DbEntity dbEnt) { 84 throw new RuntimeException ("aliases not supported"); 85 } 86 87 public void dbRelationshipAdded(DbRelationship dbRel) { 88 throw new RuntimeException ("db relationships not supported"); 89 } 90 91 92 public String createSqlString() throws Exception { 93 prepareLists(); 94 StringBuffer queryBuf = new StringBuffer ("INSERT INTO "); 95 DbEntity dbE = getEntityResolver().lookupDbEntity(query); 96 queryBuf.append(dbE.getFullyQualifiedName()).append(" ("); 97 98 int len = columnList.size(); 99 100 102 queryBuf.append(columnList.get(0)); for (int i = 1; i < len; i++) { 105 queryBuf.append(", ").append(columnList.get(i)); 106 } 107 108 queryBuf.append(") VALUES ("); 110 if (len > 0) { 111 queryBuf.append('?'); 112 for (int i = 1; i < len; i++) { 113 queryBuf.append(", ?"); 114 } 115 } 116 117 queryBuf.append(')'); 118 return queryBuf.toString(); 119 } 120 121 public org.objectstyle.cayenne.query.InsertQuery insertQuery() { 122 return (org.objectstyle.cayenne.query.InsertQuery) query; 123 } 124 125 126 protected void prepareLists() throws Exception { 127 DbEntity dbE = getEntityResolver().lookupDbEntity(query); 128 ObjectId oid = insertQuery().getObjectId(); 129 Map id = (oid != null) ? oid.getIdSnapshot() : null; 130 131 if (id != null) { 132 Iterator idIt = id.keySet().iterator(); 133 while (idIt.hasNext()) { 134 String attrName = (String ) idIt.next(); 135 DbAttribute attr = (DbAttribute) dbE.getAttribute(attrName); 136 Object attrValue = id.get(attrName); 137 columnList.add(attrName); 138 139 addToParamList(attr, attrValue); 140 } 141 } 142 143 Map snapshot = insertQuery().getObjectSnapshot(); 144 Iterator columnsIt = snapshot.keySet().iterator(); 145 while (columnsIt.hasNext()) { 146 String attrName = (String ) columnsIt.next(); 147 148 if (id != null && id.get(attrName) != null) 150 continue; 151 152 DbAttribute attr = (DbAttribute) dbE.getAttribute(attrName); 153 Object attrValue = snapshot.get(attrName); 154 columnList.add(attrName); 155 addToParamList(attr, attrValue); 156 } 157 } 158 } 159 | Popular Tags |