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 56 57 public class MySQLMaxValueIncrementer extends AbstractDataFieldMaxValueIncrementer { 58 59 60 private static final String VALUE_SQL = "select last_insert_id()"; 61 62 63 private String columnName; 64 65 66 private int cacheSize = 1; 67 68 69 private long nextId = 0; 70 71 72 private long maxId = 0; 73 74 75 78 public MySQLMaxValueIncrementer() { 79 } 80 81 87 public MySQLMaxValueIncrementer(DataSource ds, String incrementerName, String columnName) { 88 setDataSource(ds); 89 setIncrementerName(incrementerName); 90 this.columnName = columnName; 91 afterPropertiesSet(); 92 } 93 94 97 public void setColumnName(String columnName) { 98 this.columnName = columnName; 99 } 100 101 104 public String getColumnName() { 105 return this.columnName; 106 } 107 108 111 public void setCacheSize(int cacheSize) { 112 this.cacheSize = cacheSize; 113 } 114 115 118 public int getCacheSize() { 119 return this.cacheSize; 120 } 121 122 public void afterPropertiesSet() { 123 super.afterPropertiesSet(); 124 if (this.columnName == null) { 125 throw new IllegalArgumentException ("columnName is required"); 126 } 127 } 128 129 130 protected synchronized long getNextKey() throws DataAccessException { 131 if (this.maxId == this.nextId) { 132 137 Connection con = DataSourceUtils.getConnection(getDataSource()); 138 Statement stmt = null; 139 try { 140 stmt = con.createStatement(); 141 DataSourceUtils.applyTransactionTimeout(stmt, getDataSource()); 142 stmt.executeUpdate("update "+ getIncrementerName() + " set " + this.columnName + 144 " = last_insert_id(" + this.columnName + " + " + getCacheSize() + ")"); 145 ResultSet rs = stmt.executeQuery(VALUE_SQL); 147 try { 148 if (!rs.next()) { 149 throw new DataAccessResourceFailureException("last_insert_id() failed after executing an update"); 150 } 151 this.maxId = rs.getLong(1); 152 } 153 finally { 154 JdbcUtils.closeResultSet(rs); 155 } 156 this.nextId = this.maxId - getCacheSize() + 1; 157 } 158 catch (SQLException ex) { 159 throw new DataAccessResourceFailureException("Could not obtain last_insert_id()", ex); 160 } 161 finally { 162 JdbcUtils.closeStatement(stmt); 163 DataSourceUtils.releaseConnection(con, getDataSource()); 164 } 165 } 166 else { 167 this.nextId++; 168 } 169 return this.nextId; 170 } 171 172 } 173 | Popular Tags |