Sequence.java :  » Groupware » lucane » org » lucane » server » database » util » Java Open Source

Java Open Source » Groupware » lucane 
lucane » org » lucane » server » database » util » Sequence.java
/*
 * 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();
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.