1 19 20 package org.apache.cayenne.dba.sqlserver; 21 22 import java.sql.Connection ; 23 import java.sql.SQLException ; 24 import java.sql.Statement ; 25 import java.util.Collections ; 26 import java.util.Iterator ; 27 28 import org.apache.cayenne.access.OperationObserver; 29 import org.apache.cayenne.access.QueryLogger; 30 import org.apache.cayenne.access.jdbc.BatchAction; 31 import org.apache.cayenne.dba.DbAdapter; 32 import org.apache.cayenne.map.DbAttribute; 33 import org.apache.cayenne.map.EntityResolver; 34 import org.apache.cayenne.query.BatchQuery; 35 import org.apache.cayenne.query.InsertBatchQuery; 36 37 41 public class SQLServerBatchAction extends BatchAction { 42 43 public SQLServerBatchAction(BatchQuery batchQuery, DbAdapter adapter, 44 EntityResolver entityResolver) { 45 super(batchQuery, adapter, entityResolver); 46 } 47 48 public void performAction(Connection connection, OperationObserver observer) 49 throws SQLException , Exception { 50 51 boolean identityOverride = expectsToOverrideIdentityColumns(); 54 if (identityOverride) { 55 setIdentityInsert(connection, true); 56 } 57 58 try { 59 super.performAction(connection, observer); 60 } 61 finally { 62 63 66 if (identityOverride) { 68 setIdentityInsert(connection, false); 69 } 70 } 71 } 72 73 protected void setIdentityInsert(Connection connection, boolean on) 74 throws SQLException { 75 76 String flag = on ? " ON" : " OFF"; 77 String configSQL = "SET IDENTITY_INSERT " 78 + query.getDbEntity().getFullyQualifiedName() 79 + flag; 80 81 QueryLogger.logQuery(configSQL, Collections.EMPTY_LIST); 82 83 Statement statement = connection.createStatement(); 84 try { 85 statement.execute(configSQL); 86 } 87 finally { 88 try { 89 statement.close(); 90 } 91 catch (Exception e) { 92 } 93 } 94 } 95 96 99 protected boolean expectsToOverrideIdentityColumns() { 100 if (getAdapter().supportsGeneratedKeys()) { 102 return false; 103 } 104 105 if (!(query instanceof InsertBatchQuery) || query.getDbEntity() == null) { 106 return false; 107 } 108 109 Iterator it = query.getDbEntity().getAttributes().iterator(); 111 while (it.hasNext()) { 112 DbAttribute attribute = (DbAttribute) it.next(); 113 if (attribute.isGenerated()) { 114 return true; 115 } 116 } 117 118 return false; 119 } 120 } 121 | Popular Tags |