KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > jdbc > support > incrementer > AbstractSequenceMaxValueIncrementer


1 /*
2  * Copyright 2002-2005 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
17 package org.springframework.jdbc.support.incrementer;
18
19 import java.sql.Connection JavaDoc;
20 import java.sql.ResultSet JavaDoc;
21 import java.sql.SQLException JavaDoc;
22 import java.sql.Statement JavaDoc;
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 AbstractDataFieldMaxValueIncrementer {
38
39     protected long getNextKey() throws DataAccessException {
40         Connection JavaDoc con = DataSourceUtils.getConnection(getDataSource());
41         Statement JavaDoc stmt = null;
42         ResultSet JavaDoc rs = null;
43         try {
44             stmt = con.createStatement();
45             DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
46             rs = stmt.executeQuery(getSequenceQuery());
47             if (rs.next()) {
48                 return rs.getLong(1);
49             }
50             else {
51                 throw new DataAccessResourceFailureException("Sequence query did not return a result");
52             }
53         }
54         catch (SQLException JavaDoc ex) {
55             throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
56         }
57         finally {
58             JdbcUtils.closeResultSet(rs);
59             JdbcUtils.closeStatement(stmt);
60             DataSourceUtils.releaseConnection(con, getDataSource());
61         }
62     }
63
64     /**
65      * Return the database-specific query to use for retrieving a sequence value.
66      */

67     protected abstract String JavaDoc getSequenceQuery();
68
69 }
70
Popular Tags