01: /*
02: * Copyright 2004 Outerthought bvba and Schaubroeck nv
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: package org.outerj.daisy.jdbcutil;
17:
18: import org.apache.commons.logging.Log;
19:
20: import javax.sql.DataSource;
21: import java.sql.SQLException;
22: import java.sql.Connection;
23: import java.sql.PreparedStatement;
24: import java.sql.ResultSet;
25:
26: public class SqlCounter {
27: private DataSource dataSource;
28: private Log log;
29: private String tableName;
30:
31: public SqlCounter(String tableName, DataSource dataSource, Log log) {
32: this .tableName = tableName;
33: this .dataSource = dataSource;
34: this .log = log;
35: }
36:
37: public long getNextId() throws SQLException {
38: synchronized (this ) {
39: Connection conn = null;
40: PreparedStatement stmt = null;
41: ResultSet rs;
42: long maxid = 0;
43: try {
44: conn = dataSource.getConnection();
45: stmt = conn.prepareStatement("select maxid from "
46: + tableName);
47: rs = stmt.executeQuery();
48: if (!rs.next()) {
49: log
50: .info(tableName
51: + " table did not contain a record, will start numbering from 1.");
52: } else {
53: maxid = rs.getLong(1);
54: }
55:
56: maxid++;
57:
58: stmt.close();
59: stmt = conn.prepareStatement("update " + tableName
60: + " set maxid = ?");
61: stmt.setLong(1, maxid);
62: int updatedRows = stmt.executeUpdate();
63:
64: if (updatedRows == 0) {
65: stmt.close();
66: stmt = conn.prepareStatement("insert into "
67: + tableName + "(maxid) values(?)");
68: stmt.setLong(1, maxid);
69: stmt.execute();
70: }
71: } finally {
72: if (stmt != null) {
73: try {
74: stmt.close();
75: } catch (Throwable e) {
76: log.error("Error closing prepared statement.",
77: e);
78: }
79: }
80: if (conn != null) {
81: try {
82: conn.close();
83: } catch (Throwable e) {
84: log.error(
85: "Error closing datasource connection.",
86: e);
87: }
88: }
89: }
90: return maxid;
91: }
92: }
93: }
|