01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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:
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 org.springframework.dao.DataAccessException;
25: import org.springframework.dao.DataAccessResourceFailureException;
26: import org.springframework.jdbc.datasource.DataSourceUtils;
27: import org.springframework.jdbc.support.JdbcUtils;
28:
29: /**
30: * Abstract base class for incrementers that use a database sequence.
31: * Subclasses need to provide the database-specific SQL to use.
32: *
33: * @author Juergen Hoeller
34: * @since 26.02.2004
35: * @see #getSequenceQuery
36: */
37: public abstract class AbstractSequenceMaxValueIncrementer extends
38: AbstractDataFieldMaxValueIncrementer {
39:
40: protected long getNextKey() throws DataAccessException {
41: Connection con = DataSourceUtils.getConnection(getDataSource());
42: Statement stmt = null;
43: ResultSet rs = null;
44: try {
45: stmt = con.createStatement();
46: DataSourceUtils.applyTransactionTimeout(stmt,
47: getDataSource());
48: rs = stmt.executeQuery(getSequenceQuery());
49: if (rs.next()) {
50: return rs.getLong(1);
51: } else {
52: throw new DataAccessResourceFailureException(
53: "Sequence query did not return a result");
54: }
55: } catch (SQLException ex) {
56: throw new DataAccessResourceFailureException(
57: "Could not obtain sequence value", ex);
58: } finally {
59: JdbcUtils.closeResultSet(rs);
60: JdbcUtils.closeStatement(stmt);
61: DataSourceUtils.releaseConnection(con, getDataSource());
62: }
63: }
64:
65: /**
66: * Return the database-specific query to use for retrieving a sequence value.
67: */
68: protected abstract String getSequenceQuery();
69:
70: }
|