1 56 package org.objectstyle.cayenne.dba.sqlserver; 57 58 import java.sql.Connection ; 59 import java.sql.SQLException ; 60 import java.sql.Statement ; 61 import java.util.Collections ; 62 import java.util.Iterator ; 63 64 import org.objectstyle.cayenne.access.OperationObserver; 65 import org.objectstyle.cayenne.access.QueryLogger; 66 import org.objectstyle.cayenne.access.jdbc.BatchAction; 67 import org.objectstyle.cayenne.dba.DbAdapter; 68 import org.objectstyle.cayenne.map.DbAttribute; 69 import org.objectstyle.cayenne.map.EntityResolver; 70 import org.objectstyle.cayenne.query.BatchQuery; 71 import org.objectstyle.cayenne.query.InsertBatchQuery; 72 73 77 public class SQLServerBatchAction extends BatchAction { 78 79 public SQLServerBatchAction(BatchQuery batchQuery, DbAdapter adapter, 80 EntityResolver entityResolver) { 81 super(batchQuery, adapter, entityResolver); 82 } 83 84 public void performAction(Connection connection, OperationObserver observer) 85 throws SQLException , Exception { 86 87 boolean identityOverride = expectsToOverrideIdentityColumns(); 90 if (identityOverride) { 91 setIdentityInsert(connection, true); 92 } 93 94 try { 95 super.performAction(connection, observer); 96 } 97 finally { 98 99 102 if (identityOverride) { 104 setIdentityInsert(connection, false); 105 } 106 } 107 } 108 109 protected void setIdentityInsert(Connection connection, boolean on) 110 throws SQLException { 111 112 String flag = on ? " ON" : " OFF"; 113 String configSQL = "SET IDENTITY_INSERT " 114 + query.getDbEntity().getFullyQualifiedName() 115 + flag; 116 117 QueryLogger.logQuery(query.getLoggingLevel(), configSQL, Collections.EMPTY_LIST); 118 119 Statement statement = connection.createStatement(); 120 try { 121 statement.execute(configSQL); 122 } 123 finally { 124 try { 125 statement.close(); 126 } 127 catch (Exception e) { 128 } 129 } 130 } 131 132 135 protected boolean expectsToOverrideIdentityColumns() { 136 if (getAdapter().supportsGeneratedKeys()) { 138 return false; 139 } 140 141 if (!(query instanceof InsertBatchQuery) || query.getDbEntity() == null) { 142 return false; 143 } 144 145 Iterator it = query.getDbEntity().getAttributes().iterator(); 147 while (it.hasNext()) { 148 DbAttribute attribute = (DbAttribute) it.next(); 149 if (attribute.isGenerated()) { 150 return true; 151 } 152 } 153 154 return false; 155 } 156 } 157 | Popular Tags |