1 56 package org.objectstyle.cayenne.access.jdbc; 57 58 import java.sql.Connection ; 59 import java.sql.PreparedStatement ; 60 import java.sql.ResultSet ; 61 import java.sql.SQLException ; 62 import java.util.Arrays ; 63 import java.util.Collections ; 64 import java.util.Iterator ; 65 import java.util.List ; 66 import java.util.Map ; 67 68 import org.apache.commons.collections.IteratorUtils; 69 import org.objectstyle.cayenne.access.OperationObserver; 70 import org.objectstyle.cayenne.access.QueryLogger; 71 import org.objectstyle.cayenne.access.types.ExtendedTypeMap; 72 import org.objectstyle.cayenne.dba.DbAdapter; 73 import org.objectstyle.cayenne.query.SQLTemplate; 74 75 81 public class SQLTemplateSelectAction extends SQLTemplateAction { 82 83 public SQLTemplateSelectAction(SQLTemplate query, DbAdapter adapter) { 84 super(query, adapter); 85 } 86 87 90 public void performAction(Connection connection, OperationObserver observer) 91 throws SQLException , Exception { 92 93 SQLTemplateProcessor templateProcessor = new SQLTemplateProcessor(); 94 String template = extractTemplateString(); 95 boolean loggable = QueryLogger.isLoggable(query.getLoggingLevel()); 96 97 int size = query.parametersSize(); 98 99 Iterator it = (size > 0) ? query.parametersIterator() : IteratorUtils 102 .singletonIterator(Collections.EMPTY_MAP); 103 while (it.hasNext()) { 104 Map nextParameters = (Map ) it.next(); 105 106 SQLSelectStatement compiled = templateProcessor 107 .processSelectTemplate(template, nextParameters); 108 109 if (loggable) { 110 QueryLogger.logQuery(query.getLoggingLevel(), compiled.getSql(), Arrays 111 .asList(compiled.getBindings())); 112 } 113 114 long t1 = System.currentTimeMillis(); 115 116 PreparedStatement statement = connection.prepareStatement(compiled.getSql()); 120 bind(statement, compiled.getBindings()); 121 122 ResultSet rs = statement.executeQuery(); 124 ExtendedTypeMap types = adapter.getExtendedTypes(); 125 126 RowDescriptor descriptor = (compiled.getResultColumns().length > 0) 127 ? new RowDescriptor(compiled.getResultColumns(), types) 128 : new RowDescriptor(rs, types); 129 130 JDBCResultIterator result = new JDBCResultIterator( 131 connection, 132 statement, 133 rs, 134 descriptor, 135 query.getFetchLimit()); 136 137 if (!observer.isIteratedResult()) { 138 List resultRows = result.dataRows(true); 141 QueryLogger.logSelectCount(query.getLoggingLevel(), 142 resultRows.size(), 143 System.currentTimeMillis() - t1); 144 145 observer.nextDataRows(query, resultRows); 146 } 147 else { 148 try { 149 result.setClosingConnection(true); 150 observer.nextDataRows(query, result); 151 } 152 catch (Exception ex) { 153 result.close(); 154 throw ex; 155 } 156 } 157 } 158 } 159 } | Popular Tags |