1 19 20 21 package org.apache.cayenne.access.trans; 22 23 import java.sql.PreparedStatement ; 24 import java.sql.SQLException ; 25 import java.util.ArrayList ; 26 import java.util.Iterator ; 27 import java.util.List ; 28 29 import org.apache.cayenne.dba.DbAdapter; 30 import org.apache.cayenne.map.DbAttribute; 31 import org.apache.cayenne.query.BatchQuery; 32 33 39 public class InsertBatchQueryBuilder extends BatchQueryBuilder { 40 41 public InsertBatchQueryBuilder(DbAdapter adapter) { 42 super.setAdapter(adapter); 43 } 44 45 51 public void bindParameters(PreparedStatement statement, BatchQuery query) 52 throws SQLException , Exception { 53 54 List dbAttributes = query.getDbAttributes(); 55 int attributeCount = dbAttributes.size(); 56 57 for (int i = 0, j = 0; i < attributeCount; i++) { 59 DbAttribute attribute = (DbAttribute) dbAttributes.get(i); 60 if (includeInBatch(attribute)) { 61 j++; 62 Object value = query.getValue(i); 63 adapter.bindParameter(statement, value, j, attribute.getType(), attribute 64 .getScale()); 65 } 66 } 67 } 68 69 75 public List getParameterValues(BatchQuery query) { 76 List attributes = query.getDbAttributes(); 77 int len = attributes.size(); 78 List values = new ArrayList (len); 79 for (int i = 0; i < len; i++) { 80 DbAttribute attribute = (DbAttribute) attributes.get(i); 81 if (includeInBatch(attribute)) { 82 values.add(query.getValue(i)); 83 } 84 } 85 return values; 86 } 87 88 public String createSqlString(BatchQuery batch) { 89 String table = batch.getDbEntity().getFullyQualifiedName(); 90 List dbAttributes = batch.getDbAttributes(); 91 92 StringBuffer query = new StringBuffer ("INSERT INTO "); 93 query.append(table).append(" ("); 94 95 int columnCount = 0; 96 Iterator it = dbAttributes.iterator(); 97 98 while (it.hasNext()) { 99 DbAttribute attribute = (DbAttribute) it.next(); 100 101 106 if (includeInBatch(attribute)) { 107 108 if (columnCount > 0) { 109 query.append(", "); 110 } 111 query.append(attribute.getName()); 112 columnCount++; 113 } 114 } 115 116 query.append(") VALUES ("); 117 118 for (int i = 0; i < columnCount; i++) { 119 if (i > 0) { 120 query.append(", "); 121 } 122 123 query.append('?'); 124 } 125 query.append(')'); 126 return query.toString(); 127 } 128 129 134 protected boolean includeInBatch(DbAttribute attribute) { 135 140 return !attribute.isGenerated() 141 || (attribute.isPrimaryKey() && !adapter.supportsGeneratedKeys()); 142 } 143 } 144 | Popular Tags |