/*
* Lucane - a collaborative platform
* Copyright (C) 2005 Vincent Fiack <vfiack@mail15.com>
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.lucane.server.database.util;
import org.lucane.server.database.DatabaseAbstractionLayer;
import org.lucane.server.Server;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Manage database sequence, used for id generation
*/
public class Sequence
{
private String table;
private String field;
private int nextId;
/**
* Constructor
*
* @param table the table using this sequence
* @param field the generated field
*/
public Sequence(String table, String field)
{
this.table = table;
this.field = field;
this.nextId = -1;
}
/**
* Get the next id
*
* @return the next id
*/
public synchronized int getNextId()
throws SQLException
{
if(nextId < 0)
initFromDatabase();
return nextId++;
}
/**
* Load the highest id as the current one
*/
private void initFromDatabase()
throws SQLException
{
this.nextId = 0;
DatabaseAbstractionLayer layer = Server.getInstance().getDBLayer();
Connection c = layer.getConnection();
PreparedStatement select = c.prepareStatement(
"SELECT max(" + field + ")+1 FROM " + table);
ResultSet r = select.executeQuery();
if(r.next())
this.nextId = r.getInt(1);
r.close();
select.close();
c.close();
}
}
|