/**
 * User: Clinton Begin
 * Date: Jul 13, 2003
 * Time: 7:21:30 PM
 */
package com.ibatis.jpetstore.persistence.dao.sqlmapdao;

import com.ibatis.db.dao.*;
import com.ibatis.jpetstore.domain.*;
import com.ibatis.jpetstore.persistence.dao.iface.*;

public class SequenceSqlMapDao extends BaseSqlMapDao implements SequenceDao {

  /**
   * This is a generic sequence ID generator that is based on a database
   * table called 'SEQUENCE', which contains two columns (NAME, NEXTID).
   *
   * This approach should work with any database.
   *
   * @param name The name of the sequence.
   * @return The Next ID
   * @throws DaoException
   */
  public int getNextId(String name)
      throws DaoException {
    Sequence sequence = new Sequence(name, -1);

    sequence = (Sequence) executeQueryForObject("getSequence", sequence);
    if (sequence == null) {
      throw new DaoException("Error: A null sequence was returned from the database (could not get next " + name + " sequence).");
    }
    Object parameterObject = new Sequence(name, sequence.getNextId() + 1);
    executeUpdate("updateSequence", parameterObject);

    return sequence.getNextId();
  }

}
