1 56 57 package org.objectstyle.cayenne.access.trans; 58 59 import java.sql.PreparedStatement ; 60 import java.sql.SQLException ; 61 import java.util.ArrayList ; 62 import java.util.Iterator ; 63 import java.util.List ; 64 65 import org.objectstyle.cayenne.dba.DbAdapter; 66 import org.objectstyle.cayenne.map.DbAttribute; 67 import org.objectstyle.cayenne.query.BatchQuery; 68 69 75 public class InsertBatchQueryBuilder extends BatchQueryBuilder { 76 77 public InsertBatchQueryBuilder(DbAdapter adapter) { 78 super.setAdapter(adapter); 79 } 80 81 87 public void bindParameters(PreparedStatement statement, BatchQuery query) 88 throws SQLException , Exception { 89 90 List dbAttributes = query.getDbAttributes(); 91 int attributeCount = dbAttributes.size(); 92 93 for (int i = 0, j = 0; i < attributeCount; i++) { 95 DbAttribute attribute = (DbAttribute) dbAttributes.get(i); 96 if (includeInBatch(attribute)) { 97 j++; 98 Object value = query.getValue(i); 99 adapter.bindParameter(statement, value, j, attribute.getType(), attribute 100 .getPrecision()); 101 } 102 } 103 } 104 105 111 public List getParameterValues(BatchQuery query) { 112 List attributes = query.getDbAttributes(); 113 int len = attributes.size(); 114 List values = new ArrayList (len); 115 for (int i = 0; i < len; i++) { 116 DbAttribute attribute = (DbAttribute) attributes.get(i); 117 if (includeInBatch(attribute)) { 118 values.add(query.getValue(i)); 119 } 120 } 121 return values; 122 } 123 124 public String createSqlString(BatchQuery batch) { 125 String table = batch.getDbEntity().getFullyQualifiedName(); 126 List dbAttributes = batch.getDbAttributes(); 127 128 StringBuffer query = new StringBuffer ("INSERT INTO "); 129 query.append(table).append(" ("); 130 131 int columnCount = 0; 132 Iterator it = dbAttributes.iterator(); 133 134 while (it.hasNext()) { 135 DbAttribute attribute = (DbAttribute) it.next(); 136 137 142 if (includeInBatch(attribute)) { 143 144 if (columnCount > 0) { 145 query.append(", "); 146 } 147 query.append(attribute.getName()); 148 columnCount++; 149 } 150 } 151 152 query.append(") VALUES ("); 153 154 for (int i = 0; i < columnCount; i++) { 155 if (i > 0) { 156 query.append(", "); 157 } 158 159 query.append('?'); 160 } 161 query.append(')'); 162 return query.toString(); 163 } 164 165 170 protected boolean includeInBatch(DbAttribute attribute) { 171 176 return !attribute.isGenerated() 177 || (attribute.isPrimaryKey() && !adapter.supportsGeneratedKeys()); 178 } 179 } | Popular Tags |