1 16 17 package org.springframework.jdbc.support.incrementer; 18 19 import java.sql.Connection ; 20 import java.sql.ResultSet ; 21 import java.sql.SQLException ; 22 import java.sql.Statement ; 23 24 import javax.sql.DataSource ; 25 26 import org.springframework.dao.DataAccessException; 27 import org.springframework.dao.DataAccessResourceFailureException; 28 import org.springframework.jdbc.datasource.DataSourceUtils; 29 import org.springframework.jdbc.support.JdbcUtils; 30 31 54 public class HsqlMaxValueIncrementer extends AbstractDataFieldMaxValueIncrementer { 55 56 57 private String columnName; 58 59 60 private int cacheSize = 1; 61 62 private long[] valueCache = null; 63 64 65 private int nextValueIndex = -1; 66 67 68 71 public HsqlMaxValueIncrementer() { 72 } 73 74 80 public HsqlMaxValueIncrementer(DataSource ds, String incrementerName, String columnName) { 81 setDataSource(ds); 82 setIncrementerName(incrementerName); 83 this.columnName = columnName; 84 afterPropertiesSet(); 85 } 86 87 90 public void setColumnName(String columnName) { 91 this.columnName = columnName; 92 } 93 94 97 public String getColumnName() { 98 return this.columnName; 99 } 100 101 104 public void setCacheSize(int cacheSize) { 105 this.cacheSize = cacheSize; 106 } 107 108 111 public int getCacheSize() { 112 return this.cacheSize; 113 } 114 115 public void afterPropertiesSet() { 116 super.afterPropertiesSet(); 117 if (this.columnName == null) { 118 throw new IllegalArgumentException ("columnName is required"); 119 } 120 } 121 122 123 protected synchronized long getNextKey() throws DataAccessException { 124 if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) { 125 130 Connection con = DataSourceUtils.getConnection(getDataSource()); 131 Statement stmt = null; 132 try { 133 stmt = con.createStatement(); 134 DataSourceUtils.applyTransactionTimeout(stmt, getDataSource()); 135 this.valueCache = new long[getCacheSize()]; 136 this.nextValueIndex = 0; 137 for (int i = 0; i < getCacheSize(); i++) { 138 stmt.executeUpdate("insert into " + getIncrementerName() + " values(null)"); 139 ResultSet rs = stmt.executeQuery("select max(identity()) from " + getIncrementerName()); 140 try { 141 if (!rs.next()) { 142 throw new DataAccessResourceFailureException("identity() failed after executing an update"); 143 } 144 this.valueCache[i] = rs.getLong(1); 145 } 146 finally { 147 JdbcUtils.closeResultSet(rs); 148 } 149 } 150 long maxValue = this.valueCache[(this.valueCache.length - 1)]; 151 stmt.executeUpdate("delete from " + getIncrementerName() + " where " + this.columnName + " < " + maxValue); 152 } 153 catch (SQLException ex) { 154 throw new DataAccessResourceFailureException("Could not obtain identity()", ex); 155 } 156 finally { 157 JdbcUtils.closeStatement(stmt); 158 DataSourceUtils.releaseConnection(con, getDataSource()); 159 } 160 } 161 return this.valueCache[this.nextValueIndex++]; 162 } 163 164 } 165 | Popular Tags |