1 16 17 package org.springframework.jdbc.support; 18 19 import java.util.Iterator ; 20 import java.util.LinkedList ; 21 import java.util.List ; 22 import java.util.Map ; 23 24 import org.springframework.dao.DataRetrievalFailureException; 25 import org.springframework.dao.InvalidDataAccessApiUsageException; 26 27 39 public class GeneratedKeyHolder implements KeyHolder { 40 41 private final List keyList; 42 43 44 47 public GeneratedKeyHolder() { 48 this.keyList = new LinkedList (); 49 } 50 51 55 public GeneratedKeyHolder(List keyList) { 56 this.keyList = keyList; 57 } 58 59 60 public Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException { 61 if (this.keyList.size() == 0) { 62 return null; 63 } 64 if (this.keyList.size() > 1 || ((Map ) this.keyList.get(0)).size() > 1) { 65 throw new InvalidDataAccessApiUsageException( 66 "The getKey method should only be used when a single key is returned. " + 67 "The current key entry contains multiple keys: " + this.keyList); 68 } 69 Iterator keyIter = ((Map ) this.keyList.get(0)).values().iterator(); 70 if (keyIter.hasNext()) { 71 Object key = keyIter.next(); 72 if (!(key instanceof Number )) { 73 throw new DataRetrievalFailureException( 74 "The generated key is not of a supported numeric type. " + 75 "Unable to cast [" + key.getClass().getName() + "] to [" + Number .class.getName() + "]"); 76 } 77 return (Number ) key; 78 } 79 else { 80 throw new DataRetrievalFailureException("Unable to retrieve the generated key. " + 81 "Check that the table has an identity column enabled."); 82 } 83 } 84 85 public Map getKeys() throws InvalidDataAccessApiUsageException { 86 if (this.keyList.size() == 0) { 87 return null; 88 } 89 if (this.keyList.size() > 1) 90 throw new InvalidDataAccessApiUsageException( 91 "The getKeys method should only be used when keys for a single row are returned. " + 92 "The current key list contains keys for multiple rows: " + this.keyList); 93 return (Map ) this.keyList.get(0); 94 } 95 96 public List getKeyList() { 97 return keyList; 98 } 99 100 } 101 | Popular Tags |