1 56 package org.objectstyle.cayenne.access; 57 58 import java.util.Collections ; 59 import java.util.Iterator ; 60 import java.util.List ; 61 import java.util.Map ; 62 63 import org.objectstyle.cayenne.CayenneRuntimeException; 64 import org.objectstyle.cayenne.access.util.SelectObserver; 65 import org.objectstyle.cayenne.exp.Expression; 66 import org.objectstyle.cayenne.exp.ExpressionFactory; 67 import org.objectstyle.cayenne.map.DbAttribute; 68 import org.objectstyle.cayenne.map.DbEntity; 69 import org.objectstyle.cayenne.query.SelectQuery; 70 71 77 public class OptimisticLockException extends CayenneRuntimeException { 78 protected String querySQL; 79 protected DbEntity rootEntity; 80 protected Map qualifierSnapshot; 81 82 public OptimisticLockException( 83 DbEntity rootEntity, 84 String querySQL, 85 Map qualifierSnapshot) { 86 super("Optimistic Lock Failure"); 87 88 this.rootEntity = rootEntity; 89 this.querySQL = querySQL; 90 this.qualifierSnapshot = 91 (qualifierSnapshot != null) ? qualifierSnapshot : Collections.EMPTY_MAP; 92 } 93 94 public Map getQualifierSnapshot() { 95 return qualifierSnapshot; 96 } 97 98 public String getQuerySQL() { 99 return querySQL; 100 } 101 102 106 public Map getFreshSnapshot(QueryEngine engine) { 107 110 Expression qualifier = null; 111 Iterator it = rootEntity.getPrimaryKey().iterator(); 112 while (it.hasNext()) { 113 DbAttribute attribute = (DbAttribute) it.next(); 114 Expression attributeQualifier = 115 ExpressionFactory.matchDbExp( 116 attribute.getName(), 117 qualifierSnapshot.get(attribute.getName())); 118 119 qualifier = 120 (qualifier != null) 121 ? qualifier.andExp(attributeQualifier) 122 : attributeQualifier; 123 } 124 125 SelectQuery query = new SelectQuery(rootEntity, qualifier); 126 query.setFetchingDataRows(true); 127 SelectObserver observer = new SelectObserver(); 128 engine.performQueries(Collections.singletonList(query), observer); 129 List results = observer.getResults(query); 130 131 if (results == null || results.isEmpty()) { 132 return null; 133 } 134 else if (results.size() > 1) { 135 throw new CayenneRuntimeException("More than one row for ObjectId."); 136 } 137 else { 138 return (Map ) results.get(0); 139 } 140 } 141 142 145 public String getMessage() { 146 StringBuffer buffer = new StringBuffer (super.getMessage()); 147 148 if (querySQL != null) { 149 buffer.append(", SQL: [").append(querySQL.trim()).append("]"); 150 } 151 152 if (!qualifierSnapshot.isEmpty()) { 153 buffer.append(", WHERE clause bindings: ["); 154 Iterator it = qualifierSnapshot.entrySet().iterator(); 155 while (it.hasNext()) { 156 Map.Entry entry = (Map.Entry ) it.next(); 157 buffer.append(entry.getKey()).append("="); 158 QueryLogger.sqlLiteralForObject(buffer, entry.getValue()); 159 160 if (it.hasNext()) { 161 buffer.append(", "); 162 } 163 } 164 buffer.append("]"); 165 } 166 167 return buffer.toString(); 168 } 169 } 170 | Popular Tags |