KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lucane > server > database > util > Sequence


1 /*
2  * Lucane - a collaborative platform
3  * Copyright (C) 2005 Vincent Fiack <vfiack@mail15.com>
4  *
5  * This library is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU Lesser General Public License as published by the Free
7  * Software Foundation; either version 2.1 of the License, or (at your option)
8  * any later version.
9  *
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 JavaDoc;
25 import java.sql.Connection JavaDoc;
26 import java.sql.PreparedStatement JavaDoc;
27 import java.sql.ResultSet JavaDoc;
28
29 /**
30  * Manage database sequence, used for id generation
31  */

32 public class Sequence
33 {
34     private String JavaDoc table;
35     private String JavaDoc field;
36     private int nextId;
37
38     /**
39      * Constructor
40      *
41      * @param table the table using this sequence
42      * @param field the generated field
43      */

44     public Sequence(String JavaDoc table, String JavaDoc field)
45     {
46         this.table = table;
47         this.field = field;
48         this.nextId = -1;
49     }
50
51     /**
52      * Get the next id
53      *
54      * @return the next id
55      */

56     public synchronized int getNextId()
57     throws SQLException JavaDoc
58     {
59         if(nextId < 0)
60             initFromDatabase();
61
62         return nextId++;
63     }
64
65     /**
66      * Load the highest id as the current one
67      */

68     private void initFromDatabase()
69     throws SQLException JavaDoc
70     {
71         this.nextId = 0;
72
73         DatabaseAbstractionLayer layer = Server.getInstance().getDBLayer();
74         Connection JavaDoc c = layer.getConnection();
75         PreparedStatement JavaDoc select = c.prepareStatement(
76             "SELECT max(" + field + ")+1 FROM " + table);
77
78         ResultSet JavaDoc r = select.executeQuery();
79         if(r.next())
80             this.nextId = r.getInt(1);
81
82         r.close();
83         select.close();
84         c.close();
85     }
86 }
Popular Tags