01: /*
02: * Lucane - a collaborative platform
03: * Copyright (C) 2005 Vincent Fiack <vfiack@mail15.com>
04: *
05: * This library is free software; you can redistribute it and/or modify it under
06: * the terms of the GNU Lesser General Public License as published by the Free
07: * Software Foundation; either version 2.1 of the License, or (at your option)
08: * any later version.
09: *
10: * This library is distributed in the hope that it will be useful, but WITHOUT
11: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12: * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
13: * details.
14: *
15: * You should have received a copy of the GNU Lesser General Public License
16: * along with this library; if not, write to the Free Software Foundation, Inc.,
17: * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18: */
19: package org.lucane.server.database.util;
20:
21: import org.lucane.server.database.DatabaseAbstractionLayer;
22: import org.lucane.server.Server;
23:
24: import java.sql.SQLException;
25: import java.sql.Connection;
26: import java.sql.PreparedStatement;
27: import java.sql.ResultSet;
28:
29: /**
30: * Manage database sequence, used for id generation
31: */
32: public class Sequence {
33: private String table;
34: private String field;
35: private int nextId;
36:
37: /**
38: * Constructor
39: *
40: * @param table the table using this sequence
41: * @param field the generated field
42: */
43: public Sequence(String table, String field) {
44: this .table = table;
45: this .field = field;
46: this .nextId = -1;
47: }
48:
49: /**
50: * Get the next id
51: *
52: * @return the next id
53: */
54: public synchronized int getNextId() throws SQLException {
55: if (nextId < 0)
56: initFromDatabase();
57:
58: return nextId++;
59: }
60:
61: /**
62: * Load the highest id as the current one
63: */
64: private void initFromDatabase() throws SQLException {
65: this .nextId = 0;
66:
67: DatabaseAbstractionLayer layer = Server.getInstance()
68: .getDBLayer();
69: Connection c = layer.getConnection();
70: PreparedStatement select = c.prepareStatement("SELECT max("
71: + field + ")+1 FROM " + table);
72:
73: ResultSet r = select.executeQuery();
74: if (r.next())
75: this .nextId = r.getInt(1);
76:
77: r.close();
78: select.close();
79: c.close();
80: }
81: }
|