1 19 20 package org.apache.cayenne.access; 21 22 import java.util.Collections ; 23 import java.util.Iterator ; 24 import java.util.List ; 25 import java.util.Map ; 26 27 import org.apache.cayenne.CayenneRuntimeException; 28 import org.apache.cayenne.exp.Expression; 29 import org.apache.cayenne.exp.ExpressionFactory; 30 import org.apache.cayenne.map.DbAttribute; 31 import org.apache.cayenne.map.DbEntity; 32 import org.apache.cayenne.query.SelectQuery; 33 34 40 public class OptimisticLockException extends CayenneRuntimeException { 41 42 protected String querySQL; 43 protected DbEntity rootEntity; 44 protected Map qualifierSnapshot; 45 46 public OptimisticLockException(DbEntity rootEntity, String querySQL, 47 Map qualifierSnapshot) { 48 super("Optimistic Lock Failure"); 49 50 this.rootEntity = rootEntity; 51 this.querySQL = querySQL; 52 this.qualifierSnapshot = (qualifierSnapshot != null) 53 ? qualifierSnapshot 54 : Collections.EMPTY_MAP; 55 } 56 57 public Map getQualifierSnapshot() { 58 return qualifierSnapshot; 59 } 60 61 public String getQuerySQL() { 62 return querySQL; 63 } 64 65 69 public Map getFreshSnapshot(QueryEngine engine) { 71 72 75 Expression qualifier = null; 76 Iterator it = rootEntity.getPrimaryKey().iterator(); 77 while (it.hasNext()) { 78 DbAttribute attribute = (DbAttribute) it.next(); 79 Expression attributeQualifier = ExpressionFactory.matchDbExp(attribute 80 .getName(), qualifierSnapshot.get(attribute.getName())); 81 82 qualifier = (qualifier != null) 83 ? qualifier.andExp(attributeQualifier) 84 : attributeQualifier; 85 } 86 87 SelectQuery query = new SelectQuery(rootEntity, qualifier); 88 query.setFetchingDataRows(true); 89 QueryResult observer = new QueryResult(); 90 engine.performQueries(Collections.singletonList(query), observer); 91 List results = observer.getFirstRows(query); 92 93 if (results == null || results.isEmpty()) { 94 return null; 95 } 96 else if (results.size() > 1) { 97 throw new CayenneRuntimeException("More than one row for ObjectId."); 98 } 99 else { 100 return (Map ) results.get(0); 101 } 102 } 103 104 107 public String getMessage() { 108 StringBuffer buffer = new StringBuffer (super.getMessage()); 109 110 if (querySQL != null) { 111 buffer.append(", SQL: [").append(querySQL.trim()).append("]"); 112 } 113 114 if (!qualifierSnapshot.isEmpty()) { 115 buffer.append(", WHERE clause bindings: ["); 116 Iterator it = qualifierSnapshot.entrySet().iterator(); 117 while (it.hasNext()) { 118 Map.Entry entry = (Map.Entry ) it.next(); 119 buffer.append(entry.getKey()).append("="); 120 QueryLogger.sqlLiteralForObject(buffer, entry.getValue()); 121 122 if (it.hasNext()) { 123 buffer.append(", "); 124 } 125 } 126 buffer.append("]"); 127 } 128 129 return buffer.toString(); 130 } 131 } 132 | Popular Tags |