1. /*
  2. * Copyright 2002-2004 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.jdbc.support.incrementer;
  17. import java.sql.Connection;
  18. import java.sql.ResultSet;
  19. import java.sql.SQLException;
  20. import java.sql.Statement;
  21. import org.springframework.dao.DataAccessException;
  22. import org.springframework.dao.DataAccessResourceFailureException;
  23. import org.springframework.jdbc.datasource.DataSourceUtils;
  24. import org.springframework.jdbc.support.JdbcUtils;
  25. /**
  26. * Abstract base class for incrementers that use a database sequence.
  27. * Subclasses need to provide the database-specific SQL to use.
  28. * @author Juergen Hoeller
  29. * @since 26.02.2004
  30. * @see #getSequenceQuery
  31. */
  32. public abstract class AbstractSequenceMaxValueIncrementer extends AbstractDataFieldMaxValueIncrementer {
  33. protected long getNextKey() throws DataAccessException {
  34. Connection con = DataSourceUtils.getConnection(getDataSource());
  35. Statement stmt = null;
  36. ResultSet rs = null;
  37. try {
  38. stmt = con.createStatement();
  39. DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
  40. rs = stmt.executeQuery(getSequenceQuery());
  41. if (rs.next()) {
  42. return rs.getLong(1);
  43. }
  44. else {
  45. throw new DataAccessResourceFailureException("Sequence query did not return a result");
  46. }
  47. }
  48. catch (SQLException ex) {
  49. throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
  50. }
  51. finally {
  52. JdbcUtils.closeResultSet(rs);
  53. JdbcUtils.closeStatement(stmt);
  54. DataSourceUtils.closeConnectionIfNecessary(con, getDataSource());
  55. }
  56. }
  57. /**
  58. * Return the database-specific query to use for retrieving a sequence value.
  59. */
  60. protected abstract String getSequenceQuery();
  61. }